What does "dynamic type" mean in the Go interface?

The Way To Go: A thorough introduction to the Go programming language (Ivo Balbaert) contains this suggestion, which I don't quite understand:

An interface type may contain a reference to an instance of any of the types that implement the interface (the interface has a so-called dynamic type)

What is an example of this and why is it useful?

+4
source share
3 answers

Say you have an interface:

type I interface{ F() }

And two implementations of the mentioned interface:

type S struct{}
func (S) F() { }

type T struct{}
func (T) F() { }

Then:

var x I
x = S{}

Now the static type xis equal I, and its dynamic type S.

You can reassign a xvalue of another type that implements I:

x = T{}

x - I ( ), T.

IOW: - , .

+2

, (, string, int,...) , .

, , . Golang:

, Go , . : , , , , .

, .

, .

type Locker interface {
  Lock()
  Unlock()
}

Locker sync.

, , , Locker. , Locker, Foo Bar Locker.

type Foo struct {
  A string
}

func (f *Foo) String() string {
  return f.A
}

func (f *Foo) Lock() {
  // ...
}

func (f *Foo) Unlock() {
  // ...
}

type Bar struct {}

func (b *Bar) Lock() {
  // ...
}

func (b *Bar) Unlock() {
  // ...
}

, , :

, ( )

:

Locker () , (, Foo, Bar,...).

:

var lock Locker

lock = &Foo{"Foo"} // We assign an instance of type Foo to a Locker var
lock.Lock() // We can call all functions defined by the interface Locker
lock.Unlock()
lock.String() // This won't work because the Locker interface does not define the String() function, even though Foo implements it. 

lock = &Bar{}
lock.Lock()

, lock , , lock , Locker . .

?

, . https://softwareengineering.stackexchange.com/questions/108240/why-are-interfaces-useful

+1

. (int, string, bool, map, struct, slice ..), .

( ).

. - . - .

, ​​ , , , , .

. , , . , Reader , , , , , , , .

.

0

Source: https://habr.com/ru/post/1613139/


All Articles