function - 戈朗 : chaining function to returnself

标签 function go types casting wrapper

此代码不起作用,因为类型 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/

相关文章:

python - Matplotlib X 轴绘图的日期格式为 xxxx-xx-xx 00 :00:00, 如何更改为 xxxx-xx-xx?

c++ - 函数声明或原型(prototype)。我该如何定义它?

go - 为字符串取消引用运算符赋值

java - 在Java中将字节数组转换为整数,反之亦然

C的隐式类型转换

bash - 我如何在golang中运行shell命令

python - 输入: list of int elements的错误处理

MySQL。函数中的逻辑错误应返回大写字母前带有空格的字符串

python从迭代返回数组

go - 如何使用 go test -run 运行特定的 golang 测试