Pointers to an Interface
You almost never need pointers to an interface types. You should pass interfaces by value, and in doing so, the underlying data being passed can still be a pointer.
Interfaces are essentially represented with two fields at the underlying level:
- A pointer to some specific type information. You can think of it as the "type".
- A data pointer. If the stored data is a pointer, it is stored directly. If the stored data is a value, a pointer to that value is stored.
If you want interface methods to modify the underlying data, you must use pointer receivers (assign the object pointer to the interface variable).
type F interface {
f()
}
type S1 struct{}
func (s S1) f() {}
type S2 struct{}
func (s *S2) f() {}
// f1.f() cannot modify the underlying data
// f2.f() can modify the underlying data, object pointer is assigned to the interface variable f2
var f1 F = S1{}
var f2 F = &S2{}
Never use pointers to an interface, it is meaningless. In Go language, the interface itself is a reference type. In other words, the interface type itself is a pointer. For my needs, the parameter for testing only needs to be myinterface, and I only need to pass a *mystruct type (and can only pass a *mystruct type) when passing the value.
type myinterface interface{
print()
}
func test(value *myinterface){
//someting to do ...
}
type mystruct struct {
i int
}
// Implement the interface
func (this *mystruct) print(){
fmt.Println(this.i)
this.i=1
}
func main(){
m := &mystruct{0}
test(m) // Incorrect
test(*m) // Incorrect
}