golang 高级

下面的EmployeeByID函数将根据给定的员工ID返回对应的员工信息结构体的指针。我们可以使用点操作符来访问它里面的成员:

func EmployeeByID(id int) *Employee { /* ... */ }
fmt.Println(EmployeeByID(dilbert.ManagerID).Position) // "Pointy-haired boss"
id := dilbert.ID
EmployeeByID(id).Salary = 0 // fired for... no real reason

后面的语句通过EmployeeByID返回的结构体指针更新了Employee结构体的成员。如果将EmployeeByID函数的返回值从*Employee指针类型改为Employee值类型,那么更新语句将不能编译通过,因为在赋值语句的左边并不确定是一个变量(译注:调用函数返回的是值,并不是一个可取地址的变量)。

package main

type Employee struct {
    ID       int
    Name     string
    Position string
}

var emp1 = Employee{1, "a", "aa"}

func EmplyeeByID(id int) Employee {
    return emp1
}

func main() {
    EmplyeeByID(1).Name = "world" //编译报错
    a := EmplyeeByID(1)  //可以正常运行
    a.Name = "hello"
}

 当前的理解是go不允许对临时值取地址和修改

https://blog.csdn.net/btqszl/article/details/64928247

https://blog.csdn.net/yuanlaidewo000/article/details/80975033

type Matcher interface {
    Search()
}

type defaultMaster struct{
}

func (m *defaultMaster) Search() {
    fmt.Println("hello")
}

func main() {
    var dm defaultMaster
    //var matcher Matcher = dm
    // cannot use dm (type defaultMaster) as type Matcher in assignment:
    // defaultMaster does not implement Matcher (Search method has pointer receiver)
  // 当defaultMaster有pointer receiver接收者方法时,赋值给接口会报错
var matcher Matcher = &dm matcher.Search() }
原文地址:https://www.cnblogs.com/8000cabbage/p/9129475.html