【发布时间】:2017-10-15 10:24:06
【问题描述】:
在以下代码中:
type boolValue bool
func newBoolValue(val bool, p *bool) *boolValue {
*p = val
return (*boolValue)(p)
}
最后一行在做什么?
【问题讨论】:
标签: go
在以下代码中:
type boolValue bool
func newBoolValue(val bool, p *bool) *boolValue {
*p = val
return (*boolValue)(p)
}
最后一行在做什么?
【问题讨论】:
标签: go
The Go Programming Language Specification
转换是
T(x) 形式的表达式,其中T是一个类型,并且x是一个表达式,可以转换为T类型。
type boolValue bool
func newBoolValue(val bool, p *bool) *boolValue {
*p = val
return (*boolValue)(p)
}
(*boolValue)(p) 正在执行从 *bool(p 的类型)到 *boolValue(newBoolValue 函数返回值的类型)的类型转换。 Go 需要显式转换。允许转换,因为bool 是boolValue 的基础类型。
如果您只是写return p 而不进行转换,编译器错误消息会说明问题:
return p
error: cannot use p (type *bool) as type *boolValue in return argument
【讨论】:
它将*bool 类型的变量p 转换为*boolValue 类型,以匹配返回参数值。否则会抛出错误。
【讨论】:
类型在 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。无需编程。