相关疑难解决方法(0)

为什么我不能将*Struct分配给*接口?

我正在浏览Go游戏,我对指针和界面感到困惑.为什么这个Go代码没有编译?

package main

type Interface interface {}

type Struct struct {}

func main() {
    var ps *Struct
    var pi *Interface
    pi = ps

    _, _ = pi, ps
}
Run Code Online (Sandbox Code Playgroud)

即如果StructInterface,为什么不是*Struct一个*Interface

我得到的错误信息是:

prog.go:10: cannot use ps (type *Struct) as type *Interface in assignment:
        *Interface is pointer to interface, not interface
Run Code Online (Sandbox Code Playgroud)

go

133
推荐指数
2
解决办法
5万
查看次数

将结构指针强制转换为Golang中的接口指针

我有一个功能

func doStuff(inout *interface{}) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

此函数的目的是能够将任何类型的指针视为输入.但是,当我想用​​结构的指针调用它时,我有一个错误.

type MyStruct struct {
    f1 int
}
Run Code Online (Sandbox Code Playgroud)

打电话的时候 doStuff

ms := MyStruct{1}
doStuff(&ms)
Run Code Online (Sandbox Code Playgroud)

我有

test.go:38: cannot use &ms (type *MyStruct) as type **interface {} in argument to doStuff
Run Code Online (Sandbox Code Playgroud)

我该如何投射&ms兼容*interface{}

struct pointers casting interface go

26
推荐指数
1
解决办法
3万
查看次数

标签 统计

go ×2

casting ×1

interface ×1

pointers ×1

struct ×1