英文:
How to set one pointer to multiply function?
问题
如何将一个指针设置为乘法函数?
package main
import "fmt"
type Cube struct {
u int
}
func (h *Cube) space() int {
return h.u * h.u * h.u
}
func main() {
h := &Cube{
u: 10,
}
fmt.Println(h.space())
h.u = 100
fmt.Println(h.space())
}
第一个println请求返回1000,但是第二个println出错,提示左侧没有新变量的:=,但我想要的是指针使用相同的内容,只是将u的值改为100。
英文:
How can I set one pointer to multiply function?
package main
import "fmt"
type Cube struct {
u int
}
func (h *Cube) space() int {
return h.u * h.u * h.u
}
func main() {
h := Cube {
u: 10,
}
fmt.Println(h.space())
h := Cube {
u: 100,
}
fmt.Println(h.space())
}
The first request of println give back 1000, but with the second println it goes wrong telling no new variables on left side of :=
but I want the pointer to use all same just the u: to 100 change
答案1
得分: 4
:=
有两个作用,它既创建一个变量,又给它赋值。你在第二行试图创建一个名为h
的新变量,编译器告诉你它不会创建一个新变量。
只需将:=
替换为=。
英文:
:=
does two things, it creates a variable and assigns a value to it. You are trying to create a new variable called h
in the second line and the compiler is telling you that it would not create a new variable.
Just replace that :=
with =
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论