douhe2305 2018-11-18 06:29
浏览 40
已采纳

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

Working with Go I was getting various errors trying to return a string as pointer while returning another value as well. Something like this (pls. excuse for this not being running code, I just wrote it to give a sense of what I want to do since I don't know how to exactly make it work):

func A (s string) *string, int {

  // Stuff
  return &a, b
}
*c, d := A("Hi there.")

When I try various combinations to say, return the string (var. a) as a pointer I get various errors. It's easy and there's dozens of examples with a single variable returned but I'm not sure if it's possible with multiple return values.

Sorry if this seems like a very basic question, I'm still wrapping my mind around Go.

  • 写回答

3条回答 默认 最新

  • dtip91401 2018-11-18 07:16
    关注

    You can return multiple variables from a function:

    func A (s string) (string, int) {
      a := "hello world"
      b := 99
    
      return a, b
    }
    
    c, d := A("Hi there.")
    

    One thing I would like to point out is that in Go, strings aren't pointers. In languages like C, you get used to thinking about a string as a char*, however in Go, a string is treated as a primitive much like you would an int.

    This seems to trip people from time to time, however it is actually quite nice as you don't have to worry about pointers with strings.

    If you find yourself in a situation where you want to return a nil string (which you can't do because it's not a pointer), then you would return an empty string ("").

    Pointers: If you really want to do pointers...

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构