登录
首页 >  Golang >  Go问答

类型实现中的隐藏方法?

来源:stackoverflow

时间:2024-04-14 19:12:29 215浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《类型实现中的隐藏方法?》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

浏览 net/http 和相关库中的一些 go 源代码,我发现了一些让我好奇的东西。我在这里查看的是 1.12 版本。

func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
  ...
  hj, ok := rw.(http.Hijacker)
  ...
  conn, brw, err := hj.Hijack()
  ...
}

我在更多地方以及标准库之外都看到了类似的东西。这里发生了什么?在发生特定断言之前,接口实现的某些方法是否会隐藏?为什么我不能在 rw 对象上调用 hijack()


解决方案


这些方法似乎是隐藏的,因为该函数采用接口类型。 http.responsewriter 接口没有定义 hijack() 方法。这是在 http.hijacker 接口中定义的。一个具体类型可以实现多个接口。但即使这种具体类型被传递到其类型定义是接口的作用域中,其他方法也将无法访问。因此,在所质疑的示例中,执行类型断言以使 hijack() 方法可用。

一些示例(playground):

package main

import (
    "fmt"
)

type Ship interface {
    Load(containers []string)
    Condition() []string
}

type Sea interface {
    Draft() int
}

// seaShip implements the Sea and Ship interfaces
type seaShip struct {
    containers []string
}

// Load is only part of the Ship interface
func (ss *seaShip) Load(containers []string) {
    ss.containers = append(ss.containers, containers...)
}

// Condition is only part of the Ship interface
func (ss *seaShip) Condition() []string {
    return ss.containers
}

// Draft is only part of the Sea interface
func (ss *seaShip) Draft() int {
    return len(ss.containers)
}

// Pirates is not defined in any interface and therefore can only be called on the concrete type
func (ss *seaShip) Pirates() string {
    return "Help!"
}

// NewShip returns an implementation of the Ship interface
func NewShip() Ship {
    return &seaShip{}
}

func main() {
    ship := NewShip()
    ship.Load([]string{"Beer", "Wine", "Peanuts"})
    fmt.Println(ship.Condition())
    // Won't compile, method is not part of interface!
    // fmt.Println(ship.Draft())

    // Assert to make Draft() available
    sea := ship.(Sea)
    fmt.Println(sea.Draft())

    // Won't compile, methods are not part of interface!
    // fmt.Println(sea.Condition())
    // fmt.Println(sea.Pirates())

    // Assert to the concrete type makes all methods available
    ss := sea.(*seaShip)
    fmt.Println(ss.Condition())
    fmt.Println(ss.Pirates())
}

好了,本文到此结束,带大家了解了《类型实现中的隐藏方法?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>