gpt4 book ai didi

go - 与 Go 中文字的类型推断混淆

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:41 25 4
gpt4 key购买 nike

我已经开始学习 GoLang,目前正在阅读有关其使用短变量声明语法的类型推断系统的信息。

这是一个简单的程序,它引起了我的注意,但在理解上造成了一些困难:

package main

import (
"fmt"
"sort"
)

type statistics struct {
numbers []float64
mean float64
median float64
}

// Performs analytics on a slice of floating-point numbers
func GenerateStats(numbers []float64) (stats statistics) {
stats.numbers = numbers
stats.mean = sum(numbers) / float64(len(numbers))
sort.Float64s(numbers)
stats.median = median(numbers)
return stats
}

// Helper function to sum up a slice of floats
func sum(numbers []float64) (total float64) {
for _, num := range numbers {
total += num
}
return total
}

// Helper to find the median of a sorted slice of floats
func median(numbers []float64) (med float64) {
n := len(numbers)
if n%2 == 0 {
med = numbers[n/2]
} else {
med = (numbers[n/2] + numbers[(n-1)/2]) / 2 // Infer 01
}
return med
}

func main() {
nums := []float64{1, 2, 3, 3, 4}
result := generateStats(nums)
fmt.Println(result.numbers)
fmt.Println(result.mean)
fmt.Println(result.median)

b := "This is Go" + 1.9 // Infer 02
fmt.Println(b)
}

当我使用以下命令执行此程序时:$ go run <path>/statistics.go ,
我收到以下错误消息:

# command-line-arguments
<path>/statistics.go:47:20: cannot convert "This is Go" to type float64
<path>/statistics.go:47:20: invalid operation: "This is Go" + 1.9 (mismatched types string and float64)

以下是不同行为的推理:

Infer 01 : 数字文字的类型 2是根据使用它的表达式推断出来的。由于分子的类型是 float64 , Go 通过假设 2 成功执行除法作为相应的类型。因此,LHS 上变量的类型是 float64 .

我对 Infer 02 使用了相同的推理:浮点字面量的类型 1.9是根据声明推断的。但是,浮点文字不能添加到字符串中,除非它被隐式转换为字符串。所以,我不确定变量的类型 b .因此,应该引发错误。

现在,我对错误消息感到困惑。

为什么编译器会尝试将字符串文字隐式转换为 float64类型?

一般意义上:当两个操作数都是文字时,编译器如何推断类型?有哪些好的资源可以帮助我更好地理解 Go 的类型推断系统?

最佳答案

它不会尝试将其转换为 float64 类型。它只是警告字符串文字不是 float64

它可能会说字符串不是 float ,或者 float 不是字符串,但第二行用消息 mismatched types string and float64 涵盖了这两种情况。

关于go - 与 Go 中文字的类型推断混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697805/

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