invalid indirect of value (type interface {}),inferface{}中如果传递的是指针,可否取到其中的值?

453 views
Skip to first unread message

luu hoo

unread,
Apr 4, 2013, 12:16:18 AM4/4/13
to golang...@googlegroups.com
在c++里,自己定义一个结构体,然后将这个结构体实例化后通过参数传递。例如:
struct Elem{...};  
Elem e;  
std::stack<Elem> s;
s.push(e);
查看STL中的具体实现,push方法传递的是引用,内部再调用deque的push_back()方法,同样传递的是引用,最终通过容器的allocator来为已特化的类型分配空间。
也就是整个过程可以只传递引用(或指针)这样开销比较小,到最后可以为这个类型开辟空间,进行值拷贝。
但在golang里面,我自己实现了一个stack(模仿泛型,采用了inerface{}来接收外部数据结构),例如:
type Stack struct {
top  *Element
size int
}
type Element struct {
value interface{}
        next *Element
}
func (s *Stack) push(value interface{}){
...
}
s := new(Stack)
s.push(&e)
将e的指针(或引用)传递到stack当中,stack的push方法内部以interface{}接收到e后,可不可以拿到e里面的东西?不只是一个指针?
就像c++中的那样,可以拷贝数据类型中的值并分配内存空间。
我在push方法里试着写:xxx = *value 会得到invalid indirect of value (type interface {})错误信息,也就是拿不到里面的值?




steve wang

unread,
Apr 4, 2013, 5:22:38 AM4/4/13
to golang...@googlegroups.com
可以用接口查询获得interface{}对应的实际类型:
package main
import "fmt"
type T struct {
    n int
}
func value(v interface{}) *T {
    return v.(*T)
}
func main() {
    t := value(&T{10})
    fmt.Println(t.n)

qq510371827

unread,
Apr 4, 2013, 6:35:44 AM4/4/13
to golang...@googlegroups.com
谢谢您的解答。我是想实现一个通用型的数据结构。所以,在数据结构的内部实现中是没有具体的类型的(例如:*T,内部不知道具体是那个类型,所以无从对接口进行查询或断言),它只是通过interface{}接收到了一个外部的数据。我现在想得到的效果是:
将外部某个数据类型(例如一个结构体)的指针(引用)送入到interface{}中,内部再设法按照interface{}中存放的这个指针所对应的数据结构类型,来申请出对应的空间并进行拷贝传值。也就是传递引用,但能够得到其中的值完成值拷贝。

--
--
官网: http://golang-china.org/
IRC: irc.freenode.net #golang-china
@golangchina
 
---
您收到此邮件是因为您订阅了 Google 网上论坛“Golang-China”中的主题。
要退订此主题,请访问 https://groups.google.com/d/topic/golang-china/8bLwZBc8OhQ/unsubscribe?hl=zh-CN。
要退订此论坛及其所有主题,请发送电子邮件到 golang-china...@googlegroups.com
要查看更多选项,请访问 https://groups.google.com/groups/opt_out。
 
 

kane

unread,
Apr 8, 2013, 12:28:03 AM4/8/13
to golang...@googlegroups.com
可使用 reflect 获取 value 的值,并对其进行操作:

reflection 的详细解释参考:http://golang.org/doc/articles/laws_of_reflection.html

在 2013年4月4日星期四UTC+8下午12时16分18秒,luu hoo写道:

qq510371827

unread,
Apr 8, 2013, 9:58:57 AM4/8/13
to golang...@googlegroups.com
谢谢。反射的确可以。就是在这种应用场景下性能太差了。。。
Reply all
Reply to author
Forward
0 new messages