Why create a variable of an interface type? (Tour of Go, methods, 10)

I’m kind of stuck on this part of the “Tour of Go”:
https://tour.golang.org/methods/10

I understand what’s happening, but I can’t yet understand why it’s done this way?
var i I = T{"hello"}

Why would pass the variable i transitionally through the interface type?
Afterall, it seems you get the same resulting type (main.T) regardless.
It makes more sense to me to just:
i := T{"Hello"}

What am I missing logically here? I’m just trying to understand.

You are missed the type of variable.

var i I = T{"hello"}//type I
i := T{"Hello"}//type T

Edit:
The key here is show the interface can contain any type that fit the interface. If you don’t need the interface you just create variable single type.

But would you ever use that in actual code? Would there be a purpose other than educational?

Hi. https://play.golang.org/p/KLnZyLn-Zue here is the variable shapes and shape of the interface type Areable.

Great, that makes sense now. Thanks!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.