好吧用文字描述它很难,但是假设我有一个存储int指针的地图,并希望将操作的结果存储为我的哈希中的另一个键:
m := make(map[string]*int)
m["d"] = &(*m["x"] + *m["y"])
Run Code Online (Sandbox Code Playgroud)
这不起作用,并给我错误: cannot take the address of *m["x"] & *m["y"]
思考?
我知道Go没有任何构造函数,并且New func在它的位置使用了a ,但是根据这个例子.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := File{fd, name, nil, 0}
return &f
}
Run Code Online (Sandbox Code Playgroud)
他们总是回来&f.为什么只是回归File是不够的?
更新
我已经尝试将创建的对象返回到一个简单的结构,它很好.所以,我想知道返回地址是否是构造函数的标准方法.
谢谢.
根据对这个问题的回应
有关接收器的指针与值的规则是可以在指针和值上调用值方法,但只能在指针上调用指针方法
但实际上我可以对非指针值执行指针方法:
package main
import "fmt"
type car struct {
wheels int
}
func (c *car) fourWheels() {
c.wheels = 4
}
func main() {
var c = car{}
fmt.Println("Wheels:", c.wheels)
c.fourWheels()
// Here i can execute pointer method on non pointer value
fmt.Println("Wheels:", c.wheels)
}
Run Code Online (Sandbox Code Playgroud)
那么,这里有什么问题?这是一个新功能吗?或者对问题的回答是错误的?
在 go 中,当 key 不存在时,map 的值是零值。我在下面有一个简短的代码片段: 操场
package main
import (
"sync"
)
func main() {
var mm map[int]sync.Mutex
var m sync.Mutex
mm[1].Lock() // not work due to cannot call pointer method on mm[1] and cannot take the address of mm[1]
m.Lock() // work normal
}
Run Code Online (Sandbox Code Playgroud)
mm[1]和m上面有什么区别?我用reflect来检查,但看不出它们之间的区别。关于导致差异的任何线索?