Golang中如何获取一个类型作为另一个类型的类型

Golang中如何获取一个类型作为另一个类型的类型

type General string

type SpecificA General

type SpecificB General

type SpecificC General

当我编译这段代码并尝试在需要 General 类型的地方提供一个 Specific? 类型时,我遇到了以下错误…

无法使用 ot(类型为 ObjectType 的变量)作为结构体字面量中的 Type 值

有没有办法将 Specific? 类型转换为 General 类型,以便我可以测试为处理 General 类型而编写的代码?


更多关于Golang中如何获取一个类型作为另一个类型的类型的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

(已编辑)

在你的测试中尝试使用类型转换

    var a SpecificA = "abc"
    g := General(a)

Playground 链接

更多关于Golang中如何获取一个类型作为另一个类型的类型的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,SpecificASpecificBSpecificC虽然底层类型都是General,但它们是不同的命名类型,不能直接相互赋值。你需要进行显式类型转换。

package main

import "fmt"

type General string

type SpecificA General
type SpecificB General
type SpecificC General

// 处理General类型的函数
func processGeneral(g General) {
    fmt.Printf("Processing: %v\n", g)
}

func main() {
    var a SpecificA = "testA"
    var b SpecificB = "testB"
    var c SpecificC = "testC"
    
    // 需要显式类型转换
    processGeneral(General(a))  // 将SpecificA转换为General
    processGeneral(General(b))  // 将SpecificB转换为General
    processGeneral(General(c))  // 将SpecificC转换为General
    
    // 或者在需要General的地方直接使用类型转换
    var g General
    g = General(a)  // 正确:显式转换
    fmt.Println(g)
    
    // 下面的代码会编译错误
    // g = a  // 错误:不能将SpecificA直接赋值给General
}

如果你有一个结构体包含General类型的字段,也需要同样的转换:

type Container struct {
    Value General
}

func main() {
    var a SpecificA = "data"
    
    // 创建Container时需要转换
    c1 := Container{Value: General(a)}
    
    // 或者单独赋值时转换
    var c2 Container
    c2.Value = General(a)
}

注意:这种类型转换是安全的,因为它们共享相同的底层类型(string),但如果你尝试转换不兼容的类型,编译器会报错。

回到顶部