与 golang 中的类型转换混淆

muh*_*ame 3 go

最近想学习golang。但我对https://tour.golang.org/basics/13中的这段代码感到困惑。

package main

import (
    "fmt"
    "math"
)

func main() {
    var x, y int = 3, 4
    var f float64 = math.Sqrt(float64(x*x + y*y))
    var z uint = uint(f)
    fmt.Println(x, y, z)
}
Run Code Online (Sandbox Code Playgroud)

那个效果很好。然后我尝试了

var f = math.Sqrt(9 + 16)

这也有效。但是当我更改它时,var f = math.Sqrt(x*x + y*y)为什么它不起作用?它说cannot use x * x + y * y (type int) as type float64 in argument to math.Sqrt

我有 javascript 背景,但不知何故无法理解上面的代码。

Aka*_*all 7

math.Sqrt函数签名:

func Sqrt(x float64) float64
Run Code Online (Sandbox Code Playgroud)

要求你通过float64

在这种情况下:

var f float64 = math.Sqrt(float64(x*x + y*y))
Run Code Online (Sandbox Code Playgroud)

您正在float64直接转换为

在这种情况下:

var f = math.Sqrt(x*x + y*y)
Run Code Online (Sandbox Code Playgroud)

intfloat64需要时,您正在传递, 。

在这种情况下:

var f = math.Sqrt(9 + 16)
Run Code Online (Sandbox Code Playgroud)

编译器能够推断类型并float64为您传递。