golang中的make與new

來源:互聯網
上載者:User

golang 中有兩個記憶體配置機制 :new和make,二者有明顯區別.

  new:new(T)分配了零值填充的T類型的記憶體空間,並且返回其地址,即一個*T類型的值。其自身是一個指標.可用於初始化任何類型

  make: 返回一個有初始值(非零)的T類型,而不是*T,其只能用來初始化:slice,map和channel三種類型。

對比:

  1. 適用範圍:make 只能建立內建類型(slice map channel), new 則是可以對所有類型進行記憶體配置
  2. 傳回值: new 返回指標, make 返回引用
  3. 填儲值: new 填充零值, make 填充非零值

代碼:

package mainimport (    "fmt"    "reflect")type Books struct {    Title,    Content,    Author string}func main() {    a := new([]int)    fmt.Println(a)    //輸出&[],a本身是一個地址    b := make([]int, 1)    fmt.Println(b)    //輸出[0],b本身是一個slice對象,其內容預設為0    book1 := new(Books)    book1.Title = "this is book1 title"    book1.Content = "this is book1 content"    book1.Author = "this is book1 author"    book2 := Books{"this is book2 title", "this is book2 content", "this is book2 author"}    fmt.Println("book1:", book1, ",Type:", reflect.TypeOf(book1)) 
  //book1: &{this is book1 title this is book1 content this is book1 author} ,Type: *main.Books fmt.Println("book2:", book2, ",Type:", reflect.TypeOf(book2))
  //book2: {this is book2 title this is book2 content this is book2 author} ,Type: main.Books}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.