Go语言中new和 make的区别详解

Python018

Go语言中new和 make的区别详解,第1张

make it

[口语]达到预期目的,做到,获得成功,办成,及时赶到

2. [口语]病痛好转;得救,痊愈

3. 走完(一段路程)

4. [美国俚语]相处很好,受尊重;受欢迎;被接受(with)

5. [美国俚语]感到满足;正合胃口;达到理想标准

6. [粗俗语](上瘾者)吸毒

知道这些就好O(∩_∩)O~

go for it

冒一下险,大胆试一试

两者没有相似处

obj := new(StructName)  初始化Struct中的所有属性都是零值,返回的是Struct指针,效果与&StructName{}一致。

obj := StructName{Prop1:xx, Prop2:yy,...} , 初始化Struct中的所有属性,同时对指定属性赋值,返回的是Struct值对象,作为参数传递时,其属性不会被修改。

obj := &StructName{Prop1:xx, Prop2:yy,...} 同上,返回的是Struct值对象的指针,作为参数传递时,其属性可以被修改。

后面两种使用方法更加灵活。

package main

import (

"crypto/hmac"

"crypto/sha1"

"fmt"

"io"

)

func main() {

//sha1

h := sha1.New()

io.WriteString(h, "aaaaaa")

fmt.Printf("%x\n", h.Sum(nil))

//hmac ,use sha1

key := []byte("123456")

mac := hmac.New(sha1.New, key)

mac.Write([]byte("aaaaaa"))

fmt.Printf("%x\n", mac.Sum(nil))

}