gpt4 book ai didi

go - 如何将参数作为参数传播

转载 作者:行者123 更新时间:2023-12-01 22:34:43 25 4
gpt4 key购买 nike

我有以下 Golang 代码:

rows, err := common.GetAll(c, req, params, timer)
return common.GenericRowMarshal(200, rows, err)

我想弄清楚是否可以这样做:
return common.GenericRowMarshal(200, common.GetAll(c, req, params, timer)...)

但这不能编译:(

It says "not enough arguments to call..."



任何人都知道这是否可能以某种方式?

最佳答案

不,每次执行语句时,函数值和参数 调用的评估照常进行,请参阅 doc :

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

If f has a final ... parameter, it is assigned the return values of g that remain after assignment of regular parameters.



例如,以下代码有效:
package main

import "fmt"

func main() {
f(200, g())
}
func f(i int, slice ...interface{}) {
fmt.Println(i, slice) // 200 [[1 <nil>]]
}
func g() []interface{} {
return []interface{}{1, nil}
}

关于go - 如何将参数作为参数传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60371658/

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