跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 一个构造结构体的方法
未分類
31 12 月 2020

一个构造结构体的方法

一个构造结构体的方法

資深大佬 : fumeboy 8

假设要构造 testStruct 这个结构体, 常规方法是写一个 func NewStruct() testStruct 函数

这里的方法是 将这个函数 改写成结构体方法 func (s *testStruct) New() *testStruct

比较一下使用时的不同:

_ = NewStruct()  _ = (&testStruct{}).New()  

可以发现 New 这个函数被约束到了 testStruct 命名空间下, 这也是我的主要目的

完整的测试用例:

基准测试中, 两种方式的执行效率几乎一致,当 struct 很大时, (&testStruct{}).New()略有优势

package main  import (  "testing" )  type testStruct struct {  value int }  // 三种构造结构体的方法  func NewStruct() *testStruct { // 逃逸  return &testStruct{} }  func NewStruct2() testStruct { // 不逃逸 但传值时发生拷贝  return testStruct{} }  func (s *testStruct) New() *testStruct {   // 不逃逸,只拷贝了指针  // 更重要的是收束到了 testStruct 这个命名空间里  return s }    func TestNew(t *testing.T){  _ = (&testStruct{}).New()  //fmt.Println(s) }  func BenchmarkNew(b *testing.B){  for i := 0;i<b.N;i++{   _ = (&testStruct{}).New()  } }  func BenchmarkNew2(b *testing.B){  for i := 0;i<b.N;i++{   _ = NewStruct()  } } 

大佬有話說 (5)

  • 資深大佬 : vincentxue

    这种写法是受了 OO 思想的影响,最好还是不要用 OO 的思想去写 Go 。

  • 資深大佬 : sxfscool

    有啥用?

  • 資深大佬 : siteshen

    「构造函数」的本质是「无中生有」,第三种是「有中生有」,不配称作「构造函数」。

    func (s *testStruct) New() *testStruct

  • 資深大佬 : sthwrong

    都已经有了&testStruct{}, 为啥还要 New 一个?

  • 主 資深大佬 : fumeboy

    @sthwrong 初始化

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具