繁体   English   中英

go 如何从接口调用派生结构 function?

[英]go how can i call a derived struct function from interface?

首先,我是golang的新手。

我有一个接口和一个结构。 struct 有两种方法。 这些方法是“sendRequest”和“welcome”。 当我调用“sendRequest”方法时没有问题。 但我无法访问下面的“欢迎”方法。

package main

import "fmt"

type Client interface {
    sendRequest() string
}

type client struct {
}

func (c *client) sendRequest() string {
    return "Yayy!"
}

func (c *client) welcome() string {
    return "Welcome!"
}

func NewClient() Client {
    return &client{}
}

func main() {
    c := NewClient()

    fmt.Println(c.sendRequest())
    fmt.Println(c.welcome()) // not work
    fmt.Println(c.(*client).welcome()) // work
}

如果我这样调用“c.(*client).welcome()”,就没有问题。 但是以这种方式使用接口是没有意义的。

对不起我的英语不好。

您可以就地定义一个方法接口,然后转换为该接口并调用该方法。 示例( https://go.dev/play/p/fCiPaaTFECe ):

func main() {
        c := NewClient()

        type welcomer interface {
                welcome() string
        }

        println(c.(welcomer).welcome())
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM