casting - 具体结构上的类型转换与类型断言?

标签 casting go

我是golang的新手,如果这个问题太天真,请道歉。环顾四周,但找不到我的基本问题的答案。

假设我有一个具体的结构和方法,如下所示。

 type MyData struct{
     field1 string
     field2 int 
     }

func(a MyData) OperatorOnString() string{
  return a.field1.(string)
}

func(a MyData) OperatorOnInt() int{
  return a.field2.(int)
}

我的问题是,我可以键入 cast 并返回而不是执行断言吗?从我目前了解到的情况来看,断言用于接口(interface)类型的数据。但在这种情况下,我有具体的类型。我应该仍然使用断言还是可以执行 return int(a.field2) 之类的操作。我知道这个例子很简单,但我感到困惑的是何时在两种转换类型之间使用。还是这里涉及到一些 golang 惯用语?

谢谢

最佳答案

首先,type assertion只能在接口(interface)上使用:

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

但您将其应用于非接口(interface)类型字段(intstring)。这使得编译器 unhappy .

其次,如果你想从方法/函数返回类型 T,返回一个 T 类型的表达式总是足够的,你的字段已经恰好是.正确的代码很容易:

package main

import "fmt"

type MyData struct {
        field1 string
        field2 int
}

func (a MyData) OperatorOnString() string {
        return a.field1
}

func (a MyData) OperatorOnInt() int {
        return a.field2
}

func main() {
        a := MyData{"foo", 42}
        fmt.Println(a.OperatorOnString(), a.OperatorOnInt())
}

Playground


输出:

foo 42

关于casting - 具体结构上的类型转换与类型断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16442053/

相关文章:

c# - 指定的转换无效 - double 列表到 float 列表

JAVA函数重载与泛型类型问题

java - 在 Java 中打印数组

windows - Golang exec .bat 或 .exe 文件但没有得到输出

go - 具有未导出字段的结构类型之间的转换

c++ - 将特定指针转换为 std::any 指针

java - 将 ArrayList<String> 转换为 String[]

mongodb - 在带有 mgo 驱动程序的 Upsert 上使用 $setOnInsert

templates - go:根据错误代码加载模板

arrays - slice - 容量/长度?