将结构指针转换为interface{}。

huangapple go评论72阅读模式
英文:

convert struct pointer to interface{}

问题

如果我有:

   type foo struct{
   }

   func bar(baz interface{}) {
   }

上述代码是固定的 - 我不能改变 foo 或 bar。此外,在 bar 内部,baz 必须转换回 foo 结构体指针。我如何将 &foo{} 强制转换为 interface{},以便在调用 bar 时将其用作参数?

英文:

If I have:

   type foo struct{
   }

   func bar(baz interface{}) {
   }

The above are set in stone - I can't change foo or bar. Additionally, baz must converted back to a foo struct pointer inside bar. How do I cast &foo{} to interface{} so I can use it as a parameter when calling bar?

答案1

得分: 78

*foo转换为interface{}是很简单的:

f := &foo{}
bar(f) // 每种类型都实现了interface{},不需要特殊处理

要将其转换回*foo,可以使用**类型断言**:

func bar(baz interface{}) {
    f, ok := baz.(*foo)
    if !ok {
        // baz不是*foo类型。断言失败
    }

    // f是*foo类型
}

或者使用**类型切换**(类似,但适用于baz可以是多种类型的情况):

func bar(baz interface{}) {
    switch f := baz.(type) {
    case *foo: // f是*foo类型
    default: // f是其他类型
    }
}
英文:

To turn *foo into an interface{} is trivial:

f := &foo{}
bar(f) // every type implements interface{}. Nothing special required

In order to get back to a *foo, you can either do a type assertion:

func bar(baz interface{}) {
	f, ok := baz.(*foo)
	if !ok {
		// baz was not of type *foo. The assertion failed
	}

	// f is of type *foo
}

Or a type switch (similar, but useful if baz can be multiple types):

func bar(baz interface{}) {
	switch f := baz.(type) {
	case *foo: // f is of type *foo
	default: // f is some other type
	}
}

答案2

得分: 6

使用反射

reflect.ValueOf(myStruct).Interface().(newType)
英文:

use reflect

reflect.ValueOf(myStruct).Interface().(newType)

答案3

得分: 1

将结构体转换为接口可以通过以下方式实现。其中i是一个分配的数据结构。

var j interface{} = &i

英文:

Converting a struct to interface can be achieved like this.
Where i is an assign data structure.

var j interface{} = &i

答案4

得分: 0

并不完全相关,但我谷歌了问题“将接口结构转换为指针”并找到了这里。

所以,只是做个记录:要将T的接口转换为*T的接口

//
// 通过interface{}返回指向提供的结构体的指针
//
func to_struct_ptr(obj interface{}) interface{} {
vp := reflect.New(reflect.TypeOf(obj))
vp.Elem().Set(reflect.ValueOf(obj))
return vp.Interface()
}

英文:

Not fully-related, but I googled the question "convert interface struct to pointer" and get here.

So, just make a note: to convert an interface of T to interface of *T:

//
// Return a pointer to the supplied struct via interface{}
//
func to_struct_ptr(obj interface{}) interface{} {
	vp := reflect.New(reflect.TypeOf(obj))
	vp.Elem().Set(reflect.ValueOf(obj))
	return vp.Interface()
}

huangapple
  • 本文由 发表于 2014年6月26日 13:12:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/24422810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定