返回值指针语法

huangapple go评论89阅读模式
英文:

Return value pointer syntax

问题

最后一行代码的作用是将指针p转换为指向boolValue类型的指针,并返回该指针。

英文:

In the following code:

type boolValue bool

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

What is the last line doing?

答案1

得分: 3

《Go编程语言规范》

转换

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

type boolValue bool

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

(*boolValue)(p)是将p的类型*bool转换为newBoolValue函数返回值的类型*boolValue。Go语言要求显式转换。这种转换是允许的,因为boolboolValue的底层类型。

如果你只写return p而没有进行转换,编译器会报错并解释问题:

return p

错误无法将类型为*bool的p用作返回参数中的*boolValue类型
英文:

> The Go Programming Language Specification
>
> Conversions
>
> Conversions are expressions of the form T(x) where T is a type and
> x is an expression that can be converted to type T.

type boolValue bool

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

(*boolValue)(p) is doing a type conversion from *bool, the type of p, to *boolValue, the type of the newBoolValue function return value. Go requires explicit conversions. The conversion is allowed because bool is the underlying type of boolValue.

If you simply write return p without the conversion the compiler error message explains the problem:

return p

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

答案2

得分: 1

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

英文:

It is casting the variable p of type *bool to type *boolValue, in order to match the return argument value. It would throw an error otherwise.

答案3

得分: 0

在Go语言中,类型是严格的。如果你看下面的程序,我已经修改了它以适应你的变化,输出的类型将是*main.boolValue。这就是为什么在返回语句中需要将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
英文:

Type is strict in go. If you see below program which I have crafted it to your change, the Output will be of type *main.boolValue. That's why you are type casting bool type to boolValue type in the return statement.

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)
}

Output:

The type of rtnVal is  *main.boolValue

huangapple
  • 本文由 发表于 2017年5月16日 19:05:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/43999733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定