gpt4 book ai didi

go - 将函数的值作为输入参数返回给另一个

转载 作者:IT王子 更新时间:2023-10-29 01:08:18 24 4
gpt4 key购买 nike

如果我有

func returnIntAndString() (i int, s string) {...}

我有:

func doSomething(i int, s string) {...}

然后我可以成功地完成以下操作:

doSomething(returnIntAndString())

但是,假设我想向 doSomething 添加另一个参数,例如:

func doSomething(msg string, i int, s string) {...}

如果我这样调用它,编译时 Go 会报错:

doSomething("message", returnIntAndString())

与:

main.go:45: multiple-value returnIntAndString() in single-value context
main.go:45: not enough arguments in call to doSomething()

有没有办法做到这一点,或者我应该放弃并将 returnIntAndString 的返回值分配给一些引用并传递 msg 和这些值,如 doSomething(msg, code, str )

最佳答案

描述了here in the spec .它要求内部函数为所有参数返回正确的类型。不允许额外参数以及返回多个值的函数。

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters.

func Split(s string, pos int) (string, string) {
return s[0:pos], s[pos:]
}

func Join(s, t string) string {
return s + t
}

if Join(Split(value, len(value)/2)) != value {
log.Panic("test fails")
}

如果不满足那些特定条件,则需要分配返回值并单独调用函数。

关于go - 将函数的值作为输入参数返回给另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35274528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com