doumaoao0182 2015-10-28 22:58
浏览 9

类型别名在Go中如何工作? [重复]

This question already has an answer here:

I have a type wrapper in my code:

package my_package
import ""
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?


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

type Server struct {

and change the "cast"

s := Server{gin.Default()}
  • 写回答

1条回答 默认 最新

  • duanlei8119 2015-10-29 05:18

    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.

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



  • ¥15 基于ucc28019的pfc电路中芯片一直不工作
  • ¥15 yolov8在3588板子端c++推理报错
  • ¥50 unitywebrequest分段下载导致报错,如何解决?
  • ¥15 错误使用 gretna_GUI_PreprocessInterface>RunBtn_Callback
  • ¥15 WPF如何用Chart绘画出Y轴的左边数据
  • ¥15 pycharm无法查看内置代码
  • ¥15 跑hls xfopencv的例程standalone_hls_axi_example出的错误,csim没问题,c synthesis出的错误
  • ¥15 sqlserver update语句逐行生效
  • ¥20 Windows10系统命令行调用
  • ¥15 php环境如何实现国密SM2相关功能