学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《将返回值直接传递给另一个函数》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!
我调用一个返回一对的函数(在示例 os.open 中),并且我想将返回的对直接作为参数传递给另一个函数(不使用中间变量)。我尝试过以下两种方法,均未成功。 其他语言(如 f#)允许在函数调用时执行模式匹配。我怎样才能在 go 中实现同样的目标?
func checkerror(f *os.file, e error, m string) interface{} {
if e != nil {
/*print m and panic*/
}
return f
}
func f1(path string) {
checkerror(os.open(path), "can't open file") //error
}
func checkError((f *os.File, e error), m string) interface{} { //ERROR
if e != nil { /*Print m and panic*/}
return f
}
func f1(path string) {
checkError(os.Open(path), "Can't Open File")
}解决方案
允许这样做会导致不明确的行为;但您可以关闭最后一个参数并返回部分应用的函数:
func checkerror(m string) func(*os.file, error) {
return func(f *os.file, e error) {
if e != nil {
// do stuff with m
}
}
checkerror("can't open file")(os.open(path))
或者,反过来:
func checkerror(f *os.file, e error) func(string) {
return func(m string) {
if e != nil {
// do stuff with m
}
}
checkerror(os.open(path))("can't open file")
我发现它有点不一致,因为以下工作正常,但是当添加额外的位置参数时,编译器不喜欢它。
func checkerror(f *os.file, e error) interface{} {
if e != nil {
/*print m and panic*/
}
return f
}
func f1(path string) {
checkerror(os.open(path)) //error
}
显然你可以直接推送返回值,不确定你会损失多少,因为如果错误不为零你会恐慌
func checkerror(f *os.file, e error, m string) interface{} {
if e != nil {
/*print m and panic*/
}
return f
}
func f1(path string) {
file, e := os.open(path)
checkerror(file, e, "can't open file")
}
另一个想法是您可以传递该函数并在 checkerror 中完成工作
type OsFunction func(string)(* os.File, error)
func checkError(osFunction OsFunction, path string, m string) interface{} {
f, e := osFunction(path)
if e != nil {
/*Print m and panic*/
}
return f
}
func f2(path string) {
checkError2(os.Open, path, "Can't Open File")
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
