How to define a pointer in go, then pass this pointer in to a func to change its value?

huangapple go评论84阅读模式
英文:

How to define a pointer in go, then pass this pointer in to a func to change its value?

问题

import "fmt"

func zeroptr(ptr *int) {
    *ptr = 0
}

func main() {
    var oneptr *int
    *oneptr = 1
    fmt.Println("ptr is:", *oneptr)
    zeroptr(oneptr)
    fmt.Println("after calling zeroptr, the value of ptr is:", *oneptr)
}

这段代码是不起作用的,我期望的输出如下:

ptr is: 1

调用 zeroptr 后,ptr 的值为: 0

英文:
import "fmt"

func zeroptr(ptr *int) {
	*ptr = 0
}

func main() {
	oneptr * int
	*ptr = 1
	fmt.Println("ptr is :", *ptr)
	zeroptr(ptr)
	fmt.Println("after calling zeroptr, the value of ptr is :", *ptr)
}

This does not work, I am looking for output as follows:

ptr is :1

after calling zeroptr, the value of ptr is : 0

答案1

得分: 1

你应该将一个int指针传递给zeroptr函数,就像这个例子中所示:

package main

import "fmt"

func zeroptr(ptr *int) {
    *ptr = 0
}

func main() {

    var ptr int
    ptr = 1
    fmt.Println("ptr is:", ptr)
    zeroptr(&ptr)
    fmt.Println("调用zeroptr后,ptr的值为:", ptr)
}

输出结果:

ptr is: 1
调用zeroptr后,ptr的值为: 0

你可以在golang book的"What's the point of having pointers in Go?"中找到类似的例子。

英文:

You should use pass an &int to zeroptr, as in this example:

package main

import "fmt"

func zeroptr(ptr *int) {
	*ptr = 0
}

func main() {

	var ptr int
	ptr = 1
	fmt.Println("ptr is :", ptr)
	zeroptr(&ptr)
	fmt.Println("after calling zeroptr, the value of ptr is :", ptr)
}

Output:

ptr is : 1
after calling zeroptr, the value of ptr is : 0

You can see a similar example in "What's the point of having pointers in Go?", from the golang book.

答案2

得分: 0

你的指针指向什么?为了操作指针所指向的内存,你首先需要将指针指向某个地方。现在,你的ptr指向了无效的nil。你可以这样做:

func main() {
    var foo int
    var oneptr *int = &foo
    *oneptr = 1
    fmt.Println("oneptr is :", *oneptr)
    zeroptr(oneptr)
    fmt.Println("after calling zeroptr, the value of oneptr is :", *ptr)
}

将来,请在提交代码之前对其进行缩进。你可以使用gofmt程序来实现。

英文:

What does your pointer point to? In order to manipulate the memory a pointer points to, you first need to point the pointer somewhere. Right now, your ptr is pointing to nil which is invalid. You could for instance do this:

func main() {
    var foo int
    var oneptr *int = &foo
    *oneptr = 1
    fmt.Println("oneptr is :", *oneptr)
    zeroptr(oneptr)
    fmt.Println("after calling zeroptr, the value of oneptr is :", *ptr)
}

For the future, please indent your code before submitting it here. You can do this with the gofmt program.

huangapple
  • 本文由 发表于 2015年1月10日 02:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/27867148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定