create a pointer to a interface in go

To create a pointer to an interface in Go, we can use the & operator to create a pointer to a struct or any other value that implements the interface.

For example:

main.go
package main

import (
    "fmt"
)

type MyInterface interface {
    MyMethod() string
}

type MyStruct struct {
    Name string
}

func (s *MyStruct) MyMethod() string {
    return s.Name
}

func main() {
    var intf *MyInterface
    obj := &MyStruct{Name: "John"}
    intf = (*MyInterface)(obj)
    fmt.Println((*intf).MyMethod())
}
336 chars
25 lines

In the above code, we define an interface MyInterface and a struct MyStruct that implements that interface. We then create a pointer to an instance of MyInterface and assign it to a pointer to a struct that implements that interface.

Finally, we call the MyMethod() method on the interface pointer to show that we can use the interface pointer just like a regular interface value.

related categories

gistlibby LogSnag