英文:
Golang function with pointer return
问题
我刚开始使用Go语言,并且发现关于Go语言中指针的一些奇怪的事情。下面是一个让我感到困惑的例子。假设我有一个简单的模块,使用Golang编写,目录结构如下:
我有一个名为Person的模块,该模块位于person/person.go目录下,代码如下:
然后,我有另一个文件用于初始化person模块,位于person/package.go目录下,代码如下:
然后,我在main.go中运行如下代码:
问题
当我将person/package.go中的返回类型改为指针时,如下所示:
然后,main.go就会出现错误,似乎找不到我在Person中实现的函数:
请帮忙看看,有什么问题吗?谢谢。。
示例代码在以下链接中:
https://codesandbox.io/p/sandbox/heuristic-proskuriakova-hqmxv9?file=%2Fmain.go%3A7%2C1-8%2C14
英文:
I just started using Go language. and I found some strange things about pointers in the Go language. Here's an example that confused me. let's say I have a simple module with Golang as follows
The module I have is the Person module. The Person module is in the person/person.go directory with the following code
then another file to initialize the person module, is in the person/package.go directory with code like the following
then I run in main.go like the following
Problem
when I change person/package.go to return a pointer like below
then main.go becomes an error, and it seems as if it doesn't find the function that I have implemented in Person
please help, is there something wrong? Thank You ..
sample code is in the link below
https://codesandbox.io/p/sandbox/heuristic-proskuriakova-hqmxv9?file=%2Fmain.go%3A7%2C1-8%2C14
答案1
得分: 2
在GO语言中使用指针时,需要记住以下三个方面:
- 要获取变量x的地址,需要在变量前加上&符号
x:=&y
- 要读取指针的内容(而不是地址),需要在指针变量前加上*符号
a:=*b
- 要创建一个参数或返回值是指针的变量,也需要在变量类型前加上*符号
根据您的代码,以下是您遇到问题的原因。
- 如果您希望Gen方法返回一个指向接口的指针,那么您应该使用&运算符来获取地址。
func Gen() *Person {
man := NewPerson()
return &man
}
- 由于您返回的是一个接口的地址,在主函数中您必须解引用指针才能使用它,如下所示。请记住,您从该方法返回了两个值,所以您需要将返回值赋给两个变量。在这种情况下,由于我知道我们不会收到错误,我使用了丢弃符号来忽略第二个变量:
func main() {
man := person.Gen()
msg, _ := (*man).Greating("Kaido")
fmt.Println(*msg)
}
英文:
When using pointers in GO you need to remember three aspects namely:
- To get the address of a variable x we prefix the variable with an ampersand
x:=&y
- To read the contents of a pointer (not the address) we prefix a pointer variable with an asterisk
a:=*b
- To create a parameter or return value that is a pointer you also prefix the variable type with an asterisk
After looking at your code the following is the reason for the issue you are experiencing.
- If you want your Gen Method to return a pointer to an interface then you should use the & operator to get the address.
func Gen() *Person {
man := NewPerson()
return &man
}
- Since you are returning an address to an interface then in your main function you must dereference the pointer to use it, as shown below and remember you are returning two values from the method so you need to assign the return to two variable. In this case since I know that we will not receive an error, I use the discard to ignore the second variable :
func main() {
man := person.Gen()
msg, _ := (*man).Greating("Kaido")
fmt.Println(*msg)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论