Pointers 可以从函数返回部分或全部多个值作为指针吗?
使用Go时,我在尝试返回字符串作为指针的同时也返回另一个值时遇到了各种错误。类似这样的东西(请原谅,这不是运行代码,我写它只是为了让我知道我想做什么,因为我不知道如何确切地使它工作): 当我尝试各种组合时,返回字符串(var.Pointers 可以从函数返回部分或全部多个值作为指针吗?,pointers,go,Pointers,Go,使用Go时,我在尝试返回字符串作为指针的同时也返回另一个值时遇到了各种错误。类似这样的东西(请原谅,这不是运行代码,我写它只是为了让我知道我想做什么,因为我不知道如何确切地使它工作): 当我尝试各种组合时,返回字符串(var.a)作为指针,我会得到各种错误。这很简单,有几十个示例返回一个变量,但我不确定是否可以使用多个返回值 很抱歉,如果这似乎是一个非常基本的问题,我仍在思考围棋。正如《golang spec》中所说,您的部分错误,因此: 是可编译代码您可以从函数返回多个变量: func A (
a
)作为指针,我会得到各种错误。这很简单,有几十个示例返回一个变量,但我不确定是否可以使用多个返回值
很抱歉,如果这似乎是一个非常基本的问题,我仍在思考围棋。正如《golang spec》中所说,您的部分错误,因此:
是可编译代码您可以从函数返回多个变量:
func A (s string) (string, int) {
a := "hello world"
b := 99
return a, b
}
c, d := A("Hi there.")
我想指出的一点是,在Go中,字符串不是指针。在像C这样的语言中,您习惯于将字符串
视为字符*
,然而在Go中,字符串
被视为基本体,就像int
一样
这似乎会让人时不时感到困惑,但实际上它非常好,因为您不必担心带有字符串的指针
如果您发现自己需要返回一个nil
字符串(您不能这样做,因为它不是指针),那么您将返回一个空字符串(“
)
指针:如果你真的想做指针
func A (s string) (*string, int) {
a := "hello world"
b := 99
// NOTE: you have to have a variable hold the string.
// return a, &"hello world" // <- Invalid
return a, &b
}
// 'd' is of type *string
c, d := A("Hi there.")
var sPtr *string = d
var s string = *d // Use the * to dereference the pointer
func A(s字符串)(*string,int){
a:=“你好,世界”
b:=99
//注意:必须有一个变量来保存字符串。
//return a,&“hello world”//@poy:我把你的代码放在操场上,并设法让它工作起来。我不确定为什么它对我不起作用是什么问题,但可能还有其他原因。总之,稍微按摩一下,这确实起作用了:
package main
import (
"fmt"
)
func A (s *string) (*string, int) {
b := 99
return s, b
}
func main() {
r := "Hi there."
var s *string = &r
c, d := A(s)
fmt.Println(*c, d)
}
i、 e.如果只返回一个变量,则不需要在括号内(但可以)。如果返回2个或更多,则返回。是的,Result=Parameters | Type。
是您的意思,或“各种错误”的第二部分不是很有用。你会得到什么具体的错误,用什么具体的代码?嗯,字符串很有趣,但我想更一般地看一下。为了便于讨论,让我们取整数b,假设我想通过指针传递/返回它(从效率的角度来看,这很可能是毫无意义的,但这只是一个练习)在这两个变量的回报中,我会在“int”和“d”后面加一个星号吗在b后面是一个符号?这是一种处理一个返回变量的方法,但在两个返回变量上我失败了,但可能与当时的变量类型有关。
func A (s string) (*string, int) {
a := "hello world"
b := 99
// NOTE: you have to have a variable hold the string.
// return a, &"hello world" // <- Invalid
return a, &b
}
// 'd' is of type *string
c, d := A("Hi there.")
var sPtr *string = d
var s string = *d // Use the * to dereference the pointer
package main
import (
"fmt"
)
func A (s *string) (*string, int) {
b := 99
return s, b
}
func main() {
r := "Hi there."
var s *string = &r
c, d := A(s)
fmt.Println(*c, d)
}