猿问

您可以将多个值中的部分或全部作为函数的指针返回吗?

在使用 Go 时,我遇到了各种错误,试图在返回另一个值的同时返回一个字符串作为指针。像这样的东西(请原谅这不是运行代码,我只是写它来了解我想做什么,因为我不知道如何让它工作):


func A (s string) *string, int {


  // Stuff

  return &a, b

}

*c, d := A("Hi there.")

当我尝试各种组合说,返回字符串 (var. a) 作为指针时,我遇到了各种错误。这很简单,有许多返回单个变量的示例,但我不确定是否可以使用多个返回值。


抱歉,如果这看起来是一个非常基本的问题,我仍然在思考 Go。


Cats萌萌
浏览 126回答 3
3回答

幕布斯7119047

正如 golang 规范中所说,你在这部分是错误的:func A (s string) (*string, int) {     //stuff     }是可编译代码

qq_遁去的一_1

您可以从一个函数返回多个变量:func A (s string) (string, int) {&nbsp; a := "hello world"&nbsp; b := 99&nbsp; return a, b}c, d := A("Hi there.")我想指出的一件事是,在 Go 中,字符串不是指针。在像 C 这样的语言中,您习惯于将 a 视为stringa char*,但是在 Go 中,astring被视为原始类型,就像您将 an 一样int。这似乎时不时地让人绊倒,但它实际上非常好,因为你不必担心带有字符串的指针。如果您发现自己处于想要返回nil字符串的情况(您不能这样做,因为它不是指针),那么您将返回一个空字符串 ( "")。指针:如果你真的想做指针......func A (s string) (*string, int) {&nbsp; a := "hello world"&nbsp; b := 99&nbsp; // NOTE: you have to have a variable hold the string.&nbsp; // return a, &"hello world" // <- Invalid&nbsp; return a, &b}// 'd' is of type *stringc, d := A("Hi there.")var sPtr *string = dvar s string = *d // Use the * to dereference the pointer

慕容森

我把你的代码放在操场上并设法让它工作。我不确定问题出在哪里,为什么它对我不起作用,但可能还有其他原因。无论如何,稍加按摩就可以了:package mainimport (&nbsp; &nbsp; "fmt")func A (s *string) (*string, int) {&nbsp; b := 99&nbsp; return s, b}func main() {&nbsp; &nbsp; r := "Hi there."&nbsp; &nbsp; var s *string = &r&nbsp; &nbsp; c, d := A(s)&nbsp; &nbsp; fmt.Println(*c, d)}
随时随地看视频慕课网APP

相关分类

Go
我要回答