What's the meaning of interface{}?
Asked Answered
A

8

184

I'm new to interfaces and trying to do SOAP request by github

I don't understand the meaning of

Msg interface{}

in this code:

type Envelope struct {
    Body `xml:"soap:"`
}

type Body struct {
    Msg interface{}
}

I've observed the same syntax in

fmt.Println

but don't understand what's being achieved by

interface{}
Advertise answered 18/4, 2014 at 6:39 Comment(2)
interface{} is more or less the equivalent of void * in C. It can point to anything and you need a cast/type assertion to use it.Hudibrastic
What's the meaning of interface{}? See https://mcmap.net/q/135702/-what-39-s-the-meaning-of-interface.Peignoir
M
240

Note: Go 1.18 (Q1 2022) does rename interface{} to any (alias for interface{}).
See issue 49884, CL 368254 and commit 2580d0e.
See the last part of this answer.


You can refer to the article "How to use interfaces in Go" (based on "Russ Cox’s description of interfaces"):

What is an interface?

An interface is two things:

  • it is a set of methods,
  • but it is also a type

The interface{} type (or any with Go 1.18+), the empty interface is the interface that has no methods.

Since there is no implements keyword, all types implement at least zero methods, and satisfying an interface is done automatically, therefore all types satisfy the empty interface.
That means that if you write a function that takes an interface{} value as a parameter, you can supply that function with any value.

(That is what Msg represents in your question: any value)

func DoSomething(v interface{}) {
   // ...
}


func DoSomething(v any) {
   // ...
}

Here’s where it gets confusing:

inside of the DoSomething function, what is v's type?

Beginner gophers are led to believe that “v is of any type”, but that is wrong.
v is not of any type; it is of interface{} type.

When passing a value into the DoSomething function, the Go runtime will perform a type conversion (if necessary), and convert the value to an interface{} value.
All values have exactly one type at runtime, and v's one static type is interface{} (or any with Go 1.18+).

An interface value is constructed of two words of data:

  • one word is used to point to a method table for the value’s underlying type,
  • and the other word is used to point to the actual data being held by that value.

Addendum: This is were Russ's article is quite complete regarding an interface structure:

type Stringer interface {
    String() string
}

Interface values are represented as a two-word pair giving a pointer to information about the type stored in the interface and a pointer to the associated data.
Assigning b to an interface value of type Stringer sets both words of the interface value.

https://static.mcmap.net/file/mcmap/ZG-Ab5ovK1IlbRyhbmMoKnM1cFMoKmMva3/gointer2.png

The first word in the interface value points at what I call an interface table or itable (pronounced i-table; in the runtime sources, the C implementation name is Itab).
The itable begins with some metadata about the types involved and then becomes a list of function pointers.
Note that the itable corresponds to the interface type, not the dynamic type.
In terms of our example, the itable for Stringer holding type Binary lists the methods used to satisfy Stringer, which is just String: Binary's other methods (Get) make no appearance in the itable.

The second word in the interface value points at the actual data, in this case a copy of b.
The assignment var s Stringer = b makes a copy of b rather than point at b for the same reason that var c uint64 = b makes a copy: if b later changes, s and c are supposed to have the original value, not the new one.
Values stored in interfaces might be arbitrarily large, but only one word is dedicated to holding the value in the interface structure, so the assignment allocates a chunk of memory on the heap and records the pointer in the one-word slot.


Issue 33232 seems to point out to any as an alias to interface{} in Go 1.18 (Q1 2022)

Russ Cox explains:

  1. 'any' being only for constraints is a detail that will be in every writeup of generics - books, blog posts, and so on. If we think we are likely to allow it eventually, it makes sense to allow it from the start and avoid invalidating all that written material.

  2. 'any' being only for constraints is an unexpected cut-out that reduces generality and orthogonality of concepts. It's easy to say "let's just wait and see", but prescribing uses tends to create much more jagged features than full generality. We saw this with type aliases as well (and resisted almost all the proposed cut-outs, thankfully).

  3. If 'any' is allowed in generics but not non-generic code, then it might encourage people to overuse generics simply because 'any' is nicer to write than 'interface{}', when the decision about generics or not should really be made by considering other factors.

  4. If we allow 'any' for ordinary non-generic usage too, then seeing interface{} in code could serve as a kind of signal that the code predates generics and has not yet been reconsidered in the post-generics world. Some code using interface{} should use generics. Other code should continue to use interfaces.
    Rewriting it one way or another to remove the text 'interface{}' would give people a clear way to see what they'd updated and hadn't. (Of course, some code that might be better with generics must still use interface{} for backwards-compatibility reasons, but it can still be updated to confirm that the decision was considered and made.)

That thread also includes an explanation about interface{}:

It's not a special design, but a logical consequence of Go's type declaration syntax.

You can use anonymous interfaces with more than zero methods:

func f(a interface{Foo(); Bar()}) {
   a.Foo()
   a.Bar()
}

Analogous to how you can use anonymous structs anywhere a type is expected:

func f(a struct{Foo int; Bar string}) {
   fmt.Println(a.Foo)
   fmt.Println(a.Bar)
}

An empty interface just happens to match all types because all types have at least zero methods.

Removing interface{} would mean removing all interface functionality from the language if you want to stay consistent / don't want to introduce a special case.

Metatarsal answered 18/4, 2014 at 6:54 Comment(11)
What do you mean by "two words of data"? Specifically, what does the "word" mean?Fireeater
@Fireeater I have completed the answer to illustrate those two words (32-bits points).Metatarsal
@Mingyu: VonC is referring to a word in the computer architecture sense -- a collection of bits that define a fixed size piece of data. Word size is governed by the processor architecture you're using.Gehlbach
dear all, when you perform a ` type switch, does golang create always a copy of the object? e.g. when you do myObj := myInterface.(ObjType), you create a copy and assign it to myObj, right? so myObj` and the actual object referenced by myInterface are separated values of the same thing. BUT in the other hand if you do myObj := myInterface.(*ObjType), assuming you have pointers, you copy a pointer and, by the ancients laws of the pointers, if you have two pointers at the same thing, using either of them you can makes changes on the underlying sole object.Dur
@Vic please ask a separate question, for all to answer.Metatarsal
thanks @Metatarsal for your reply... the true is that i am tired of getting downpost when i ask things.. people most of the time tell me that i should read the docs... i will recall your suggestion if i feel with will to properly write a post for it... but i really can't think on another way to ask. So thanks anyway and excuse my low will. You are welcome to take a look at this: #45577801 to clarify why i don't like to ask.Dur
@vic no problem, and sorry for your previous bad experience as an asker. It's just that comments are a bad fit for questions and answers.Metatarsal
@Metatarsal really appreciate your feedback on this... is an upvote to the my will. Thanks.Dur
this : medium.com/golangspec/interfaces-in-go-part-i-4ae53a97479c and this : medium.com/golangspec/interfaces-in-go-part-ii-d5057ffdb0a6 are also good for readingMobilize
New to Go. While I see lotsa explanation on empty interfaces, I find little info on best-practices when/how to use them, and what pros/cons, considerations are. Most interested in best-practices for libraries and frameworks right now.Stoddart
Thank you @VonC! I have just created a separate Question about this, which can be found here: #65717732Stoddart
S
46

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface (interface{} is an empty interface).
In your example, Msg field can have value of any type.

Example:

package main

import (
    "fmt"
)

type Body struct {
    Msg interface{}
}

func main() {
    b := Body{}
    b.Msg = "5"
    fmt.Printf("%#v %T \n", b.Msg, b.Msg) // Output: "5" string
    b.Msg = 5

    fmt.Printf("%#v %T", b.Msg, b.Msg) //Output:  5 int
}

Go Playground

Seismograph answered 9/12, 2014 at 15:41 Comment(1)
Simplest one liner I have ever got. all above answers are great but this one stands out.Saxony
E
17

There are already good answers here. Let me add my own too for others who want to understand it intuitively:


Interface

Here's an interface with one method:

type Runner interface {
    Run()
}

So any type that has a Run() method satisfies the Runner interface:

type Program struct {
    /* fields */
}

func (p Program) Run() {
    /* running */
}

func (p Program) Stop() {
    /* stopping */
}
  • Although the Program type has also a Stop method, it still satisfies the Runner interface because all that is needed is to have all of the methods of an interface to satisfy it.

  • So, it has a Run method and it satisfies the Runner interface.


Empty Interface

Here's a named empty interface without any methods:

type Empty interface {
    /* it has no methods */
}

So any type satisfies this interface. Because, no method is needed to satisfy this interface. For example:

// Because, Empty interface has no methods, following types satisfy the Empty interface
var a Empty

a = 5
a = 6.5
a = "hello"

But, does the Program type above satisfy it? Yes:

a = Program{} // ok

interface{} is equal to the Empty interface above.

var b interface{}

// true: a == b

b = a
b = 9
b = "bye"

As you see, there's nothing mysterious about it but it's very easy to abuse. Stay away from it as much as you can.


https://play.golang.org/p/A-vwTddWJ7G

Explosive answered 5/6, 2018 at 20:58 Comment(1)
The type Runner interface is unused in the Go playground example.Peignoir
M
13

It's called the empty interface and is implemented by all types, which means you can put anything in the Msg field.

Example :

body := Body{3}
fmt.Printf("%#v\n", body) // -> main.Body{Msg:3}

body = Body{"anything"}
fmt.Printf("%#v\n", body) // -> main.Body{Msg:"anything"}

body = Body{body}
fmt.Printf("%#v\n", body) // -> main.Body{Msg:main.Body{Msg:"anything"}}

This is the logical extension of the fact that a type implements an interface as soon as it has all methods of the interface.

Mooned answered 18/4, 2014 at 6:41 Comment(2)
means it could be an int to user defined structure ??Advertise
"This is the logical extension of the fact that a type implements an interface as soon as it has all methods of the interface." A quite interesting idea for me to understand the design of interface in Go.Mammary
C
11

From the Golang Specifications:

An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.

A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:

interface{}

The concepts to graps are:

  1. Everything has a Type. You can define a new type, let's call it T. Let's say now our Type T has 3 methods: A, B, C.
  2. The set of methods specified for a type is called the "interface type". Let's call it in our example: T_interface. Is equal to T_interface = (A, B, C)
  3. You can create an "interface type" by defining the signature of the methods. MyInterface = (A, )
  4. When you specify a variable of type, "interface type", you can assign to it only types which have an interface that is a superset of your interface. That means that all the methods contained in MyInterface have to be contained inside T_interface

You can deduce that all the "interface types" of all the types are a superset of the empty interface.

Chivy answered 18/4, 2014 at 7:6 Comment(0)
P
1

An example that extends the excellent answer by @VonC and the comment by @NickCraig-Wood. interface{} can point to anything and you need a cast/type assertion to use it.

package main

import (
    . "fmt"
    "strconv"
)

var c = cat("Fish")
var d = dog("Bone")

func main() {
    var i interface{} = c
    switch i.(type) {
    case cat:
        c.Eat() // Fish
    }

    i = d
    switch i.(type) {
    case dog:
        d.Eat() // Bone
    }

    i = "4.3"
    Printf("%T %v\n", i, i) // string 4.3
    s, _ := i.(string)      // type assertion
    f, _ := strconv.ParseFloat(s, 64)
    n := int(f)             // type conversion
    Printf("%T %v\n", n, n) // int 4
}

type cat string
type dog string
func (c cat) Eat() { Println(c) }
func (d dog) Eat() { Println(d) }

i is a variable of an empty interface with a value cat("Fish"). It is legal to create a method value from a value of interface type. See https://golang.org/ref/spec#Interface_types.

A type switch confirms i interface type is cat("Fish") . See https://golang.org/doc/effective_go.html#type_switch. i is then reassigned to dog("Bone"). A type switch confirms that i interface’s type has changed to dog("Bone") .

You can also ask the compiler to check that the type T implements the interface I by attempting an assignment: var _ I = T{}. See https://golang.org/doc/faq#guarantee_satisfies_interface and https://mcmap.net/q/137520/-ensure-a-type-implements-an-interface-at-compile-time-in-go.

All types implement the empty interface interface{}. See https://talks.golang.org/2012/goforc.slide#44 and https://golang.org/ref/spec#Interface_types . In this example, i is reassigned, this time to a string "4.3".i is then assigned to a new string variable s with i.(string) before s is converted to a float64 type f using strconv. Finally f is converted to n an int type equal to 4. See What is the difference between type conversion and type assertion?

Go's built-in maps and slices, plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly. See https://golang.org/doc/faq#generics.

Peignoir answered 12/6, 2020 at 5:4 Comment(1)
N
0

Interface is a type which is unknown at compile time

It is a contract between object and the struct type to satisfy with common functionality or common functionality acting on different types of struct objects for example in the below code PrintDetails is a common functionality acting on different types of structs as Engineer,Manager, Seniorhead please find the example code interface examplehttps://play.golang.org/p/QnAqEYGiiF7

Nara answered 30/8, 2021 at 12:10 Comment(2)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker.Underpainting
Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.Marzi
C
-1
  • A method can bind to any type(int, string, pointer, and so on) in GO

  • Interface is a way of declear what method one type should have, as long as A type has implement those methods, this can be assigned to this interface.

  • Interface{} just has no declear of method, so it can accept any type

Cedillo answered 15/12, 2021 at 5:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.