亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
When to Use make()
Key Differences Summary
首頁(yè) 后端開發(fā) Golang go中的make()和new()有什么區(qū)別?

go中的make()和new()有什么區(qū)別?

Jun 19, 2025 am 01:00 AM
go

在Go語(yǔ)言中,new()用于分配并返回指向任意類型的零值指針,而make()則專門用于初始化切片、映射和通道。具體區(qū)別如下:1.new(T)分配內(nèi)存并返回*T類型指針,適用于需要指向結(jié)構(gòu)體或基礎(chǔ)類型的指針且無(wú)需復(fù)雜初始化的場(chǎng)景;2.make()僅用于slice、map和chan類型,它不僅分配內(nèi)存還進(jìn)行內(nèi)部結(jié)構(gòu)設(shè)置,使這些類型可直接使用;3.new()返回的是指針,make()返回的是實(shí)際類型的非指針實(shí)例;4.new()適用于任何類型,make()僅限特定內(nèi)置類型。兩者用途不同,不可互換。

What is the difference between make() and new() in Go?

In Go, make() and new() are both built-in functions used for allocation, but they serve different purposes and are used in different contexts. Understanding when to use each is key to writing effective Go code.


When to Use new()

new(T) is used to allocate memory for a type T and returns a pointer to the zero value of that type. It doesn’t initialize the value beyond setting it to its default (like 0 for integers, false for booleans, nil for pointers).

For example:

p := new(int)
fmt.Println(*p) // prints: 0

This creates a pointer to an integer with the initial value of 0. You’ll typically use new() when you need a pointer to a struct or a basic type, especially if you want to avoid manually initializing it to zero yourself.

A common case might be:

type User struct {
    Name string
    Age  int
}

u := new(User)
// u is now a pointer to a User with empty Name and Age 0

Just remember, new() gives you a pointer, and it only zeroes out the memory — it doesn’t do any custom initialization logic.


When to Use make()

make() is specifically for initializing slices, maps, and channels. These types require more than just allocating memory — they need internal structure setup to be usable.

You can't use make() for arbitrary types; it only works with those three built-in types.

Examples:

s := make([]int, 0, 5) // slice with length 0, capacity 5
m := make(map[string]int) // empty map ready to use
c := make(chan int) // unbuffered channel

Using make() ensures these types are properly initialized so you can start appending to slices, putting values into maps, or sending data through channels right away.

If you tried to declare them without make() like this:

var m map[string]int
m["key"] = 42 // panic: assignment to entry in nil map

You'd get a runtime error because the map wasn't initialized.


Key Differences Summary

  • Purpose:

    • new() allocates memory and zeroes it.
    • make() initializes certain types (slice, map, chan) so they're ready for use.
  • Return Type:

    • new(T) returns *T.
    • make() returns the actual type (T, not *T).
  • Usability:

    • new() works with any type.
    • make() only works with slices, maps, and channels.

So while both help with memory management, they’re not interchangeable — make() handles more complex setup for specific types, and new() simply allocates and zeros.


That’s basically it. They each have their own role, and once you know what kind of type you're dealing with, choosing between them becomes straightforward.

以上是go中的make()和new()有什么區(qū)別?的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁(yè)開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
Switch語(yǔ)句如何運(yùn)行? Switch語(yǔ)句如何運(yùn)行? Jul 30, 2025 am 05:11 AM

Go的switch語(yǔ)句默認(rèn)不會(huì)貫穿執(zhí)行,匹配到第一個(gè)條件后自動(dòng)退出。1.switch以關(guān)鍵字開始并可帶一個(gè)值或不帶值;2.case按順序從上到下匹配,僅運(yùn)行第一個(gè)匹配項(xiàng);3.可通過逗號(hào)列出多個(gè)條件來(lái)匹配同一case;4.不需要手動(dòng)添加break,但可用fallthrough強(qiáng)制貫穿;5.default用于未匹配到的情況,通常放最后。

如何從GO中筑巢的循環(huán)中斷 如何從GO中筑巢的循環(huán)中斷 Jul 29, 2025 am 01:58 AM

在Go中,要跳出嵌套循環(huán),應(yīng)使用標(biāo)簽化break語(yǔ)句或通過函數(shù)返回;1.使用標(biāo)簽化break:將標(biāo)簽置于外層循環(huán)前,如OuterLoop:for{...},在內(nèi)層循環(huán)中使用breakOuterLoop即可直接退出外層循環(huán);2.將嵌套循環(huán)放入函數(shù)中,滿足條件時(shí)用return提前返回,從而終止所有循環(huán);3.避免使用標(biāo)志變量或goto,前者冗長(zhǎng)易錯(cuò),后者非推薦做法;正確做法是標(biāo)簽必須位于循環(huán)之前而非之后,這是Go語(yǔ)言中跳出多層循環(huán)的慣用方式。

使用上下文軟件包進(jìn)行取消和超時(shí) 使用上下文軟件包進(jìn)行取消和超時(shí) Jul 29, 2025 am 04:08 AM

USECONTEXTTOPROPAGATECELLATION ANDDEADEADLINESACROSSGOROUTINES,ENABLINGCOOPERATIVECELLATIONININHTTPSERVERS,背景任務(wù),andChainedCalls.2.withContext.withContext.withCancel(),CreatseAcancellableBableBablebableBableBableBablebableContExtandAndCandExtandCallCallCancelLcancel()

建立表演者為第三方API的客戶 建立表演者為第三方API的客戶 Jul 30, 2025 am 01:09 AM

使用專用且配置合理的HTTP客戶端,設(shè)置超時(shí)和連接池以提升性能和資源利用率;2.實(shí)現(xiàn)帶指數(shù)退避和抖動(dòng)的重試機(jī)制,僅對(duì)5xx、網(wǎng)絡(luò)錯(cuò)誤和429狀態(tài)碼重試,并遵守Retry-After頭;3.對(duì)靜態(tài)數(shù)據(jù)如用戶信息使用緩存(如sync.Map或Redis),設(shè)置合理TTL,避免重復(fù)請(qǐng)求;4.使用信號(hào)量或rate.Limiter限制并發(fā)和請(qǐng)求速率,防止被限流或封禁;5.將API封裝為接口,便于測(cè)試、mock和添加日志、追蹤等中間件;6.通過結(jié)構(gòu)化日志和指標(biāo)監(jiān)控請(qǐng)求時(shí)長(zhǎng)、錯(cuò)誤率、狀態(tài)碼和重試次數(shù),結(jié)合Op

如何在Go中正確復(fù)制切片 如何在Go中正確復(fù)制切片 Jul 30, 2025 am 01:28 AM

要正確復(fù)制Go中的切片,必須創(chuàng)建新的底層數(shù)組,而不是直接賦值;1.使用make和copy函數(shù):dst:=make([]T,len(src));copy(dst,src);2.使用append與nil切片:dst:=append([]T(nil),src...);這兩種方法都能實(shí)現(xiàn)元素級(jí)別的復(fù)制,避免共享底層數(shù)組,確保修改互不影響,而直接賦值dst=src會(huì)導(dǎo)致兩者引用同一數(shù)組,不屬于真正復(fù)制。

Jul 30, 2025 am 02:51 AM

Go使用time.Time結(jié)構(gòu)體處理日期和時(shí)間,1.格式化和解析使用參考時(shí)間“2006-01-0215:04:05”對(duì)應(yīng)“MonJan215:04:05MST2006”,2.創(chuàng)建日期使用time.Date(year,month,day,hour,min,sec,nsec,loc)并指定時(shí)區(qū)如time.UTC,3.時(shí)區(qū)處理通過time.LoadLocation加載位置并用time.ParseInLocation解析帶時(shí)區(qū)的時(shí)間,4.時(shí)間運(yùn)算使用Add、AddDate和Sub方法進(jìn)行加減和計(jì)算間隔,

如何將template.parsefs與GO嵌入? 如何將template.parsefs與GO嵌入? Jul 30, 2025 am 12:35 AM

使用template.ParseFS與embed包可將HTML模板編譯進(jìn)二進(jìn)制文件。1.導(dǎo)入embed包并用//go:embedtemplates/.html將模板文件嵌入embed.FS變量;2.調(diào)用template.Must(template.ParseFS(templateFS,"templates/.html"))解析所有匹配的模板文件;3.在HTTP處理器中通過tmpl.ExecuteTemplate(w,"home.html",nil)渲染指定

如何在GO中導(dǎo)入本地軟件包? 如何在GO中導(dǎo)入本地軟件包? Jul 30, 2025 am 04:47 AM

要正確導(dǎo)入本地包,需使用Go模塊并遵循目錄結(jié)構(gòu)與導(dǎo)入路徑匹配原則。1.使用gomodinit初始化模塊,如gomodinitexample.com/myproject;2.將本地包放在子目錄中,如mypkg/utils.go,包聲明為packagemypkg;3.在main.go中通過完整模塊路徑導(dǎo)入,如import"example.com/myproject/mypkg";4.避免相對(duì)導(dǎo)入、路徑不匹配或命名沖突;5.對(duì)于模塊外的包可使用replace指令。只要確保模塊初始化

See all articles