duan1930 2018-03-24 12:17
浏览 84
已采纳

用Go语言返回其结构地址的方法

In my attempt to create a linked list data structure I've declared two structs.

package main

import "fmt"

type listElement struct {
    data int         
    next *listElement 
}

type List struct {
    first *listElement 
    last  *listElement 
    len   int          
}

I want to create a method that returns an empty list. So far I've only been able to create the function

func new() *List {
    return &List{}
}

This is the same result I've seen in multiple data structure repositories. Is it possible to create a method List.new() that returns a new empty list?

  • 写回答

1条回答 默认 最新

  • douzhang8144 2018-03-24 17:37
    关注

    Yes, of course you can define a method that returns a List value, but since you need a List value to call a method this is kind of awkward:

    package main
    
    type List struct{}
    
    func (List) New1() *List {
        return &List{}
    }
    
    func (*List) New2() *List {
        return &List{}
    }
    
    func main() {
        _ = List{}.New1()
        _ = (&List{}).New2()
        _ = (*List)(nil).New2()
    }
    

    I honestly don't see how this is better than a NewList function, which is idiomatic in Go:

    func NewList() *List {
        return &List{}
    }
    

    If your package is called list, name the function New instead, so it is called as list.New().

    The arguments and bodies would be the same in all cases. They only differ in how they are called, and the package function is easiest to use. (See the link in JimB's comment for one more variant that is slightly different.)

    It seems you have not yet read Effective Go, which suggests most of the above.

    The function to make new instances of ring.Ring—which is the definition of a constructor in Go—would normally be called NewRing, but since Ring is the only type exported by the package, and since the package is called ring, it's called just New, which clients of the package see as ring.New.

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

报告相同问题?

悬赏问题

  • ¥15 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图