gpt4 book ai didi

go - 将接口(interface)转换为结构

转载 作者:IT王子 更新时间:2023-10-29 01:08:28 29 4
gpt4 key购买 nike

type SipField interface {
Info() (id, name, defaultValue string, length int)
}

type Field string

func (f *Field) Get() string {
return string(*f)
}

func (f *Field) Set(s string) {
*f = Field(s)
}

type CommandID Field

func (cid *CommandID) Info() (id, name, defaultValue string, length int) {
return "", "command ID", "", 2
}

type Language Field

func (l *Language) Info() (id, name, defaultValue string, length int)
{
return "", "language", "019", 3
}

func InitField(f interface{}, val string) error {
sipField, ok := f.(SipField)
if !ok {
return errors.New("InitField: require a SipField")
}
_, _, defaultValue, length := sipField.Info()
field, ok := f.(*Field)
if !ok {
return errors.New("InitField: require a *Field")
}
return nil
}

InitField() 函数中,如何将 interface{} 转换为 Field(CommandID, Language...)?我尝试通过

直接输入断言
field, ok := f.(*Field)

但它不起作用。我尝试使用 unsafe.Pointer 但也失败了。

最佳答案

看看Type assertions Go引用中的章节。它指出:

x.(T)

More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T.

类型 CommandID 和 Field 与 Type identity 中描述的不同.

A defined type is always different from any other type.

CommandId 和 Fields 这两种类型的定义如 Type definitions 中所述.

A type definition creates a new, distinct type with the same underlying type and operations as the given type, and binds an identifier to it.

TypeDef = identifier Type .

你只能做

field, ok := f.(*CommandID)

field, ok := f.(*Language)

正如@mkopriva 在评论中提到的,您可以稍后将类型转换为 *Field 但这似乎不是您的目标。

其他解决方案是引入具有 Set 和 Get 方法的 Field 接口(interface)。然后,您需要为每种实现类型提供一个实现。

关于go - 将接口(interface)转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49448302/

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