gpt4 book ai didi

Go 自动类型转换 - 将 interface{} 与具体类型进行比较

转载 作者:行者123 更新时间:2023-12-01 22:07:14 26 4
gpt4 key购买 nike

如果我想比较两种类型 - 字符串 接口(interface){} 我通常写:

package main

import "log"

func main() {
var p1 interface{}
var p2 string

p1 = "123"
p2 = "123"

if v, ok := p1.(string); ok {
log.Println(v == p2)
} else {
log.Println("false")
}
}

我认为 时是保存变体类型(p1)!=字符串 .
但是如果我写它是正确的吗?:
package main

import "log"

func main() {
var p1 interface{}
var p2 string

p1 = "123"
p2 = "123"

log.Println(p1 == p2)
}

如果 type(p1) != string 没有错误。但它是相同的变体还是我应该写上一个?

最佳答案

您的直接问题的简短回答是 是的 ,尽管原始代码(您问题中的第一个片段)显示了对类型检查的更多考虑,因此从软件工程的角度来看它可能更正确。如果不了解更多上下文,很难说清楚。

根据Go spec :

Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

A value x of non-interface type X and a value t of interface type T are comparable when values of type X are comparable and X implements T. They are equal if t's dynamic type is identical to X and t's dynamic value is equal to x.



我相信您的要求属于此处第二段的条款。

关于Go 自动类型转换 - 将 interface{} 与具体类型进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60810966/

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