Go中的类型别名是什么意思?

huangapple go评论73阅读模式
英文:

How does type aliases work in Go?

问题

我在我的代码中有一个类型包装器:

package my_package
import "github.com/gin-gonic/gin"
type Server *gin.Engine

在我的包内使用它是完全正常的,比如:

func NewServer() Server {
    s := Server(gin.Default())
    // 我可以在这里调用 *gin.Engine 的函数而没有问题
    return s
}

然而,在我的测试套件中(位于另一个包中),我导入了我的包并获取了 Server 类型。然而,当我尝试调用一些“继承”的函数时,它不起作用。

server_test.go:68: server.ServeHTTP 未定义类型 my_package.Server 没有 ServeHTTP 字段或方法

发生了什么

**编辑**

我找到的解决方法与下面 @jiang-yd 的答案有关
将类型更改为嵌入结构体

```go
type Server struct {
    *gin.Engine
}

并更改“转换”

s := Server{gin.Default()}
英文:

I have a type wrapper in my code:

package my_package
import "github.com/gin-gonic/gin"
type Server *gin.Engine

It works perfectly fine to use it within my package like:

func NewServer() Server {
    s:= Server(gin.Default())
    // I can call *gin.Engine functions on my s here without problems
    return s
}

In my test suite (which resides in another package) I import my package and get the Server type. However, when I try to call some "inherited" functions on it doesn't work.

server_test.go:68: server.ServeHTTP undefined (type my_package.Server has no field or method ServeHTTP)

What's going on?

EDIT

The solution I found is related to @jiang-yd answer below:
Change the type to a embedding struct

type Server struct {
    *gin.Engine
}

and change the "cast"

s := Server{gin.Default()}

答案1

得分: 1

在官方文档中,有两种类型,静态类型和底层类型。Server 是你的静态类型,*gin.Engine 是底层类型。在大多数情况下,Golang 中只使用静态类型,所以 Server*gin.Engine 是两种类型。请查看 Golang 的规范

在你的问题中,这并不能帮助你。在你的情况下,你需要使用 Golang 的嵌入结构体,它可以帮助你从一个结构体继承所有方法到另一个结构体。

英文:

in official document, there are two kinds of type, static type and underlying type. Server is your static type and *gin.Engine is the underlying type. most place in golang just use static type, so Server and *.gin.Engine are two types. check the golang spec

well it not help you in your problem. in your situation, you need embedding struct of golang, which help you inherit all method from one struct to another.

huangapple
  • 本文由 发表于 2015年10月29日 06:58:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/33403041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定