此代码不起作用,因为类型 amount 不是 int,我想知道为什么 go 不知道如何处理此自定义类型?
我知道
var x amount = 8
将修复此函数,因为它需要一个数量,但我的老师坚持认为这两个函数是 100% 等效的,在我看来,它们不是因为上述类型错误。
我希望有人能帮我解决这个问题。
type amount int
func main() {
x := 8
y := foo(x)
fmt.Println(y)
}
func foo(x amount) amount {
return x * x
}
这段代码确实有效,似乎是同一种组合。
func Auth1(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request){
fmt.Println("here is the authorization code")
c := mcookie.GetCookie(req)
cl := db[c.Value]
if !cl.Loggedin {
http.Redirect(w, req, "/", http.StatusSeeOther)
}
h(w, req)
}
}
最佳答案
函数 foo() 需要一个 amount 类型作为参数,您所要做的就是将 x 作为数量传递,如下所示: y : = foo(金额(x))
工作示例:https://play.golang.org/p/xkbp43vjyA
在 Go 中,类型非常重要,例如,如果你正在创建一个类型 amount 是因为你可能想要添加比 int 定义方法更多的行为,所以如果您的函数正在接收一个数量,无论它是否与 int 兼容,您都必须传递该类型。
关于function - 戈朗 : chaining function to returnself,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145371/