首页 > 其他分享 >Go - Creating Struct Instances

Go - Creating Struct Instances

时间:2023-10-07 11:47:51浏览次数:35  
标签:sausheong Creating reference instance Person Instances person Go struct

Problem: You want to create an instance of a struct.


Solution: Create a struct instance directly using the name of the struct, or a pointer to a struct instance using the new keyword.

 

There are two ways to create an instance of a struct. The first is to directly use the name of the struct:

type   Person   struct   { 
      Id       int 
      Name     string 
      Email    string 
} 

person   :=   Person {}

This creates an empty struct instance, which you can populate subsequently by accessing the struct fields:

person . Id   =   1 
person . Name   =   "Chang  Sau  Sheong" 
person . Email   =   "[email protected]"

A quicker way is to create and initialize the struct instance at the same time:

person   :=   Person { 1 ,   "Chang  Sau  Sheong" ,   "[email protected]" }

This is pretty straightforward. However, you need to specify all field values.
You can also make the code clearer by indicating the name of the data field during initialization. When you do this, you can leave out field values:

person   :=   Person { 
      Id :      1 , 
      Email :   "[email protected]" , 
}

 

To create a reference to a struct instance you can use the address operator ( & ):

person   :=   & Person { 
      Id :      1 , 
      Name :    "Chang  Sau  Sheong" , 
      Email :   "[email protected]" , 
}

This brings us to the second way of creating struct instances, which is to use the new built - in function. The new function is used for more than creating struct instances though; it can be used to create references to a specified type. In this case, you’re using it to create a reference to a struct instance:

person   :=   new ( Person )

When creating a struct instance this way, new returns a reference to the struct instance and not the actual instance itself. In other words, this is equivalent to the following code:

person   :=   & Person {}

 

Should you pass a struct instance by copy or by reference? The usage is quite clear; you would want to pass by reference if you want the function to modify the struct instance in some way. If not, both ways work. In this case, wouldn’t it be better to always pass by reference so you don’t need to think too much about it? Not really, because there is a difference in performance. There are two ways we normally pass struct instances around.

The first is passing a struct instance down to a function either by copy or by reference.

func   byCopyDown ( p   Person )   { 
      _   =   fmt . Sprintf ( "%v" ,   p ) 
} 

func   byReferenceDown ( p   * Person )   { 
      _   =   fmt . Sprintf ( "%v" ,   p ) 
}

Passing down by copy is faster than passing down by reference.

Now let’s look at the second direction, which is passing the struct instance by copy or by reference back from the function to the caller.

func   byCopyUp ()   Person   { 
      return   Person { 
          Id :           1 , 
          GivenName :    "Sau  Sheong" , 
          FamilyName :   "Chang" , 
          Email :        "[email protected]" , 
      } 
} 

func   byReferenceUp ()   * Person   { 
      return   & Person { 
          Id :           1 , 
          GivenName :    "Sau  Sheong" , 
          FamilyName :   "Chang" , 
          Email :        "[email protected]" , 
      } 
}

Passing up by copy is much faster than passing up by reference.

In general, if you don’t need to pass structs around by reference, you should stick with passing by copy.

 

标签:sausheong,Creating,reference,instance,Person,Instances,person,Go,struct
From: https://www.cnblogs.com/zhangzhihui/p/17745890.html

相关文章

  • Strimzi Kafka Bridge(桥接)实战之三:自制sdk(golang版本)
    欢迎访问我的GitHub这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos本篇概览本文是《StrimziKafkaBridge(桥接)实战》的第三篇,前文咱们掌握了StrimziKafkaBridge的基本功能:基于http提供各种kafka消息的服务此刻,如果想通过http接口调......
  • WIN11 安装 SQL Server 2019,SQLSERVER2022, MYSQL 8.0 ,Docker,Mongodb失败故障分析
    最近研究数据库性能调优遇到各种数据库各种装不上,不知道熬了多少根软白沙,熬了多少颗张三疯,问了多少AI,查了多少网页,熬了两天,终于搞明白了一件事:那就是WIN11ONARM(因为拿的是MACPROM2做.NET平台开发安装)SQLSERVER2019,SQLSERVER2022,MYSQL8.0,Docker,Mongodb失败故障分析,最终极......
  • 基于goravel的CMS,企业官网通用golang后台管理系统
    2023年9月11日10:47:00仓库地址:https://gitee.com/open-php/zx-goravel-websiteCMS,企业官网通用PHP后台管理系统框架介绍GoravelSCUI后端开发组件go1.20Goravel1.13数据库sql(使用最新日期文件)goravel\doc\sql_bakmysql8.0前端开发组件scui1.6.9nodev14.21.......
  • 超能组合:python 的开发效率 + go 的并发 + shell 的短小精悍
    工具思维:利用合适的工具做合适的事情,然后合理地加以组合。在”谈谈程序员应当具备的技术思维“一文中谈到了工具思维。本文对工具思维作一发挥运用。批量下载图片程序员总是有点”美图“爱好的。由于程序员通常又是比较”懒惰“的(可没有那个耐心和体力去一页页点开再点击按......
  • Go - Parsing Time Displays Into Structs
     funcmain(){str:="4:31am+0800onOct1,2021"layout:="3:04pm-0700onJan2,2006"t,err:=time.Parse(layout,str)iferr!=nil{log.Println("C......
  • Go - Formatting time
     funcmain(){t:=time.Now()fmt.Println(t.Format("3:04PM"))fmt.Println(t.Format("Jan02,2006"))}Whenyourunthisyoushouldseesomethinglike:1:45PMOct23,2021That’ssimpl......
  • Go - Measuring Lapsed Time
    Problem: Youwanttomeasurethelapsedtimeandmakesurethatitisaccurate.Solution: UsethemonotonicclockintheTimestructtofindthelapsedtime. TheTimestructcontainsthedatabutonlyundercertaincircumstances.IfyoucreateaTimes......
  • go通过pprof定位groutine泄漏
    日常开发中除了会出现Panic、ErrorInfo等通过日志很容易捕捉到的错误,还会出现内存泄漏、CPU激增等日志难以捕捉的问题。今天小老虎就给大家介绍下如何使用pprof去捕捉内存、CPU这些日志难以排查到的问题。pprof的访问pprof是Golang的性能分析工具,可以帮助我们查看程序在运行过程中C......
  • 基于Django的智慧旅游系统的设计与实现-计算机毕业设计源码+LW文档
    摘 要在各学校的教学过程中,智慧旅游系统是一项非常重要的事情。随着计算机多媒体技术的发展和网络的普及。采用当前流行的B/S模式以及3层架构的设计思想通过Python技术来开发此系统的目的是建立一个配合网络环境的智慧旅游系统,这样可以有效地解决智慧旅游管理信息混乱的局面。......
  • go语言ent教程:使用zerolog定制ent日志
    背景:ent开始debug模式后,可以输出日志,但是我们想为ent接入zerolog,该怎么做呢? 一、引入zerologgoget-ugithub.com/rs/zerolog 二、自定义zerolog配置customLog:=func(args...any){str:=fmt.Sprintf("%v",args)fmt.Println(str)......