Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert interface{} to object in golang?

Tags:

go

type Human struct {
     Name string
}

func (t *Human) GetInfo() {
    fmt.Println(t.Name)
}

func main() {
    var p1 interface{}
    p1 = Human{Name:"John"}
    //p1.GetInfo() 
}

now,p1's typs is interface{}, but i want get a Human object.

How to do? i can call p1.GetInfo()

like image 969
emitle Avatar asked Dec 31 '13 05:12

emitle


People also ask

What does interface {} mean in Golang?

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.

What is type assertion in Golang?

A type assertion provides access to an interface value's underlying concrete value. t := i.(T) This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t . If i does not hold a T , the statement will trigger a panic.

What is empty interface in Golang?

The interface type that specifies zero methods is known as the empty interface: interface{} An empty interface may hold values of any type. (Every type implements at least zero methods.) Empty interfaces are used by code that handles values of unknown type.


2 Answers

You can use a type assertion to unwrap the value stored in an interface variable. From your example, p1.(Human) would extract a Human value from the variable, or panic if the variable held a different type.

But if your aim is to call methods on whatever is held in the interface variable, you probably don't want to use a plain interface{} variable. Instead, declare the methods you want for the interface type. For instance:

type GetInfoer interface {
    GetInfo()
}

func main() {
    var p1 GetInfoer
    p1 = &Human{Name:"John"}
    p1.GetInfo()
}

Go will then make sure you only assign a value with a GetInfo method to p1, and make sure that the method call invokes the method appropriate to the type stored in the variable. There is no longer a need to use a type assertion, and the code will work with any value implementing the interface.

like image 138
James Henstridge Avatar answered Nov 11 '22 16:11

James Henstridge


You can do a type assertion inline:

p1.(*Human).GetAll()

http://play.golang.org/p/ldtVrPnZ79

Or you can create a new variable to hold a Human type.

like image 25
Eve Freeman Avatar answered Nov 11 '22 16:11

Eve Freeman