【问题标题】:Return value pointer syntax返回值指针语法
【发布时间】:2017-10-15 10:24:06
【问题描述】:

在以下代码中:

type boolValue bool

func newBoolValue(val bool, p *bool) *boolValue {
    *p = val
    return (*boolValue)(p)
}

最后一行在做什么?

【问题讨论】:

    标签: go


    【解决方案1】:

    The Go Programming Language Specification

    Conversions

    转换是T(x) 形式的表达式,其中T 是一个类型,并且 x 是一个表达式,可以转换为T 类型。

    type boolValue bool
    
    func newBoolValue(val bool, p *bool) *boolValue {
        *p = val
        return (*boolValue)(p)
    }
    

    (*boolValue)(p) 正在执行从 *boolp 的类型)到 *boolValuenewBoolValue 函数返回值的类型)的类型转换。 Go 需要显式转换。允许转换,因为boolboolValue 的基础类型。

    如果您只是写return p 而不进行转换,编译器错误消息会说明问题:

    return p
    
    error: cannot use p (type *bool) as type *boolValue in return argument
    

    【讨论】:

      【解决方案2】:

      它将*bool 类型的变量p 转换为*boolValue 类型,以匹配返回参数值。否则会抛出错误。

      【讨论】:

      【解决方案3】:

      类型在 go 中是严格的。如果您看到下面我为您的更改精心制作的程序,输出将是*main.boolValue 类型。这就是您在 return 语句中将 bool 类型转换为 boolValue 类型的原因。

      package main
      
      import (
          "fmt"
          "reflect"
      )
      
      type boolValue bool
      
      func main() {
          var a bool = true
          b := &a
          rtnVal := newBoolValue(a, b)
          fmt.Println("The type of rtnVal is ", reflect.TypeOf(rtnVal))
      }
      
      func newBoolValue(val bool, p *bool) *boolValue {
          *p = val
          return (*boolValue)(p)
      }
      

      输出:

      The type of rtnVal is  *main.boolValue
      

      【讨论】:

      • 或者,更简单的是,你可以做编译器所做的事情。查看函数声明中的返回类型。在package main 中是*boolValue。无需编程。
      猜你喜欢
      • 2018-05-30
      • 2014-10-29
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      相关资源
      最近更新 更多