简体   繁体   中英

Pointer and Struct member function

Invoke function

When I define a struct Lock and a function Test with the struct Lock as the function receiver

type Lock struct {
}

func (self Lock) Test() {
    fmt.Println("Test Func")
}

I found that I can call this function with a Lock struct pointer

lock := &Lock{}
lock.Test()

The same, if I define a struct Lock and a function Test as the Lock 's pointer as the receiver, I can call this function through Lock struct instance.

So whatever the receiver is the struct itself or the struct pointer, I can call this function through the both? What's the reason. As my comprehension, the struct and the struct pointer are totally two different type!

Interface

If a define a interface Locker like this

type Locker interface {
    Test()
}

And define a struct Lock and a function Test with the struct instance as the receiver, I can't assign a struct pointer variable to a Locker interface var.

On the contrary, If a define a struct Lock and a function Test with the struct pointer as the receiver, assign a struct instance variable to a Locker interface var can work!

I'm so confused about the language design. Can anybody give me some advice?

Usually, Go does things for you under the hood and this is typically one of those cases.

When you define a function with a struct as receiver and you pass it a pointer to the struct, then Go does the conversion for you: it passes a copy of the struct pointed to.

When you define a function with a pointer as a receiver and you pass it a struct, Go creates a pointer to this struct.

However, when defining an interface, you're working on types: The Locker interface defines a type which implements the function Test() .

And with interfaces, Go won't help you: if your type doesn't implement a method, then it does not implement the interface. No hidden conversion here.

Usually, it's better to be clear about what you want and how you want it and thus preventing Go from doing those weird conversions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM