Golang中如何正确调用函数

Golang中如何正确调用函数 我在调用函数时遇到了问题,该函数的参数是另一个函数的返回值。

正常工作的函数

cmd := func(apiResp interface{}, err error) { ... }

我可以这样调用该函数

cmd(cli.ServerVersion(context.Background()))

其中 cli.ServerVersion() == func (cli *Client) ServerVersion(ctx context.Context) (types.Version, error)。两个返回类型传递给 cmd 函数。

当给 cmd 添加第三个参数时,问题就出现了。

cmd := func(apiResp interface{}, err error, path string) { ... }

这样调用

cmd(cli.ServerVersion(context.Background()), "the/file/path")

会导致以下错误:

multiple-value cli.ServerVersion() in single-value context


- ```go
not enough arguments in call to cmd
go version go1.11.4 darwin/amd64

更多关于Golang中如何正确调用函数的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

这是一个多重赋值的情况:
https://gobyexample.com/multiple-return-values
在"你可以一次性声明多个变量"部分有最通用的示例:
https://gobyexample.com/variables

更多关于Golang中如何正确调用函数的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你好

Go语言的一个特性是能够通过先调用返回相同数量参数(且类型兼容)的函数,来使用可变数量的参数调用另一个函数。请参阅这篇帖子:[使用Println打印字符串和函数返回值](https://forum.golangbridge.org/t/print-string-and-return-values-of-a-function-with-println/11527/5)

在Go语言中,当函数返回多个值时,不能直接在另一个需要多个参数的函数调用中使用。cli.ServerVersion() 返回两个值 (types.Version, error),但 cmd 函数现在需要三个参数 (interface{}, error, string)

你需要将 cli.ServerVersion() 的返回值分别存储到变量中,然后将这些变量连同第三个参数一起传递给 cmd 函数。

以下是正确的调用方式:

// 获取函数的多个返回值
version, err := cli.ServerVersion(context.Background())

// 使用这些返回值调用cmd函数
cmd(version, err, "the/file/path")

或者,如果你不需要在调用 cmd 之外使用这些返回值,可以使用一个语句完成:

// 使用临时变量
version, err := cli.ServerVersion(context.Background())
cmd(version, err, "the/file/path")

如果你想要更简洁的写法,可以使用匿名函数:

func() {
    version, err := cli.ServerVersion(context.Background())
    cmd(version, err, "the/file/path")
}()

错误的原因在于:当你写 cmd(cli.ServerVersion(context.Background()), "the/file/path") 时,Go编译器将 cli.ServerVersion(context.Background()) 视为一个单一的值上下文,但它实际上返回两个值。这导致了 “multiple-value cli.ServerVersion() in single-value context” 错误,同时由于只传递了两个参数(一个多值表达式和一个字符串)给需要三个参数的函数,也出现了 “not enough arguments” 错误。

回到顶部