douzhan4522 2015-08-31 03:38
浏览 48
已采纳

在Go中,假设有一个接口{},我知道该接口实现了什么接口,如何将其转换为它

My current problem is that I am implementing data-structures and I have written iterators for them. I have visible interfaces for my data-structures, iterators, and all other required objects. In the back I have concrete implementations which I wish to hide from the end user.

This requires many of my functions to return interface{} objects so that I can store any type of object (and leave validation up to the end-user).

One problem I have is that I iterate over a Graph. My iterator{} for my graph implementation returns a concrete vertex type but the Iterator interface returns interface{}. Since the end-users can only my base Vertex interface I have to try to convert to a Vertex interface so they can use it.

Here is the smallest example that I could think of at this point which illustrates my issue:

package main

import (
    "fmt"
    "strconv"
)

type Base interface {
    Required() string
}

type Concrete struct {
    _data int
}
func (con *Concrete) Required() string {
    return strconv.Itoa(con._data)
}

func convert(val interface{}) *Base {
    if con,ok := val.(*Base); ok {
        return con
    }
    return nil
}

func main() {
    conc := new(Concrete)
    conc._data = 5

    base := convert(conc)

    fmt.Println(base)
}

In the code above I really wish that convert would convert the type to *Base. The function convert will return the value nil instead of the lovely value I wish it to be.


Edit: Removed unused code, I thought I had already removed it but I guess not.

  • 写回答

1条回答 默认 最新

  • dongsou0083 2015-08-31 03:38
    关注

    Now that I have finished writing this long explanation I had an idea and figured out the solution:

    func convert(val interface{}) Base {
        if con,ok := val.(Base); ok {
            return con
        }
        return nil
    }
    

    Don't try to cast to a pointer but rather just the Base interface.

    I am not sure why this is the case. When I do reflect.TypeOf(val) inside of convert it gives the output

    *main.Concrete
    

    I hope that other people find this useful and that someone else can answer the why portion of this answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记