Explicação detalhada da diferença entre golang make e new

  índice

Um novo

Dois, faça

Três, a diferença entre new e make


Muitos amigos não entendiam por que existem duas funções para alocar memória quando eles entraram em contato com Golang pela primeira vez: novo e fazer. Como diz o ditado: A existência é razoável. Vamos explicar em detalhes a diferença entre os dois. 

Um novo

Observe a declaração da função primeiro:

func new(Type) *Type

new é uma função incorporada de Golang, que é usada para alocar memória. O primeiro parâmetro é o tipo e o valor de retorno é o ponteiro do tipo. Seu valor é inicializado com "zero" (valor zero correspondente ao tipo, int é inicializado com 0, bool inicializado com falso, etc.).

Por exemplo:

package main
import "fmt"

func main() {
	id := new(int)
	name := new(string)
	flag := new(bool)
	fmt.Printf("id type: %T  value: %v\n", id, *id)
	fmt.Printf("name type: %T  value: %v\n", name, *name)
	fmt.Printf("flag type: %T  value: %v\n", flag, *flag)
}

Resultado:

id type: *int  value: 0
name type: *string  value: 
flag type: *bool  value: false

Como pode ser visto no exemplo acima, o valor "zero" inicializado difere de acordo com o tipo.O número inteiro é inicializado com 0, a string é inicializada para vazio e o tipo bool é inicializado para falso. 

Dois, faça

Observe a declaração da função primeiro: 

func make(t Type, size ...IntegerType) Type

make é uma função incorporada do Golang. É usado apenas para alocar e inicializar os tipos de objetos de fatia, mapa e canal. Todos os três tipos são estruturas. O valor de retorno é um tipo, não um ponteiro.

Estrutura do código-fonte da fatia:

type slice struct {
    array unsafe.Pointer  //指针
    len   int             //长度
    cap   int             //容量
}

Estrutura do código-fonte do mapa:

// A header for a Go map.
type hmap struct {
	// Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go.
	// Make sure this stays in sync with the compiler's definition.
	count     int // # live cells == size of map.  Must be first (used by len() builtin)
	flags     uint8
	B         uint8  // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
	noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
	hash0     uint32 // hash seed

	buckets    unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
	oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
	nevacuate  uintptr        // progress counter for evacuation (buckets less than this have been evacuated)

	extra *mapextra // optional fields
}

Estrutura da fonte do canal:

type hchan struct {
	qcount   uint           // total data in the queue
	dataqsiz uint           // size of the circular queue
	buf      unsafe.Pointer // points to an array of dataqsiz elements
	elemsize uint16
	closed   uint32
	elemtype *_type // element type
	sendx    uint   // send index
	recvx    uint   // receive index
	recvq    waitq  // list of recv waiters
	sendq    waitq  // list of send waiters

	// lock protects all fields in hchan, as well as several
	// fields in sudogs blocked on this channel.
	//
	// Do not change another G's status while holding this lock
	// (in particular, do not ready a G), as this can deadlock
	// with stack shrinking.
	lock mutex
}

 Por exemplo:

package main

import "fmt"

func main() {
	//map
	fmt.Println("map:")
	var nameId = make(map[string]int, 0)
	fmt.Printf("nameId \ntype: %#v\n", nameId)
	nameId["Golang"] = 1
	nameId["C++"] = 2
	nameId["PHP"] = 3

	for name, id := range nameId {
		fmt.Printf("name = %v, id = %v\n", name, id)
	}
	// slice
	var hobby = make([]string, 2, 100) // 其中 2是长度,100是容量
	hobby[0] = "打篮球"
	hobby[1] = "乒乓球"
	fmt.Println("\nslice:")
	fmt.Printf("length = %v  caps = %v\n", len(hobby), cap(hobby))
	for _, name := range hobby {
		fmt.Println(name)
	}
	// channel
	ch := make(chan int, 3)
	ch <- 1
	ch <- 2
	ch <- 8
	close(ch)
	fmt.Println("\nchannel:")
	for val := range ch { // 遍历数据
		fmt.Println(val)
	}
}

Resultado:

[root@localhost test]# go run main.go 
map:
nameId 
type: map[string]int{}
name = Golang, id = 1
name = C++, id = 2
name = PHP, id = 3

slice:
length = 2  caps = 100
打篮球
乒乓球

channel:
1
2
8
[root@localhost test]#

Três, a diferença entre new e make

1. Tanto new quanto make são usados ​​para alocar memória;

2. Tanto o novo quanto o make alocam memória no heap;

3. New aloca memória para tipos de ponteiro e o valor de retorno é um ponteiro do tipo de alocação.New não pode alocar memória diretamente para fatia, mapa e canal;

4. Make é usado apenas para a inicialização de slice, map e channel, e o valor de retorno é o próprio tipo, não um ponteiro;

 

Acho que você gosta

Origin blog.csdn.net/u011074149/article/details/111567784
Recomendado
Clasificación