ホームページ  >  記事  >  バックエンド開発  >  Go 言語の new キーワードと make キーワードの違いについて話しましょう

Go 言語の new キーワードと make キーワードの違いについて話しましょう

PHPz
PHPz転載
2023-03-27 16:16:17782ブラウズ

この記事では、非常に一般的な面接の質問を紹介します。どのくらい一般的ですか?これが多くの面接の出発点となる可能性があります。これが、new と make の 2 つの組み込み関数の違いです。

Go 言語の new キーワードと make キーワードの違いについて話しましょう

実は、問題自体は複雑ではなく、簡単に言うと、 new はメモリを割り当てるだけで、make はスライス、マップ、チャンの初期化にのみ使用できます。について詳しくご紹介しましょう。

new

new は、メモリを割り当て、そのメモリへのポインタを返す組み込み関数です。

関数のシグネチャは次のとおりです:

ソース コード

// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
func new(Type) *Type

上記のコードからわかるように、新しい関数は 1 つのパラメーターのみを受け入れます。これは型であり、その型のメモリ アドレスへのポインタを返します。

同時に、新しい関数は割り当てられたメモリをゼロ、つまり型のゼロ値に設定します。

使用

new 関数を使用して変数にメモリ領域を割り当てます:

p1 := new(int)
fmt.Printf("p1 --> %#v \n ", p1) //(*int)(0xc42000e250) 
fmt.Printf("p1 point to --> %#v \n ", *p1) //0

var p2 *int
i := 0
p2 = &i
fmt.Printf("p2 --> %#v \n ", p2) //(*int)(0xc42000e278) 
fmt.Printf("p2 point to --> %#v \n ", *p2) //0

上記のコードは同等です、new(int) 割り当てられた領域を int のゼロ値、つまり 0 に初期化し、int のポインタを返します。これは、ポインタを直接宣言して初期化するのと同じ効果があります。

もちろん、新しい関数はシステムのデフォルトのデータ型にスペースを割り当てるだけでなく、以下に示すように、カスタム型も新しい関数を使用してスペースを割り当てることができます:

type Student struct {
   name string
   age int
}
var s *Student
s = new(Student) //分配空间
s.name = "zhangsan"
fmt.Println(s)

これは新しい関数。返されるのは常に、割り当てられた型のメモリ アドレスを指す型のポインタです。新しい関数はメモリ空間を割り当てるだけで、メモリ空間を初期化しないことに注意してください。

#make

#make はメモリ割り当てにも使用されますが、new とは異なり、スライス、マップ、チャンのメモリ作成とその型にのみ使用されます。これは 3 つの型そのものであり、ポインタ型ではありません。これら 3 つの型自体は参照型であるため、ポインタを返す必要はありません。

関数のシグネチャは次のとおりです:

ソース コード
// The make built-in function allocates and initializes an object of type
// slice, map, or chan (only). Like new, the first argument is a type, not a
// value. Unlike new, make's return type is the same as the type of its
// argument, not a pointer to it. The specification of the result depends on
// the type:
// Slice: The size specifies the length. The capacity of the slice is
// equal to its length. A second integer argument may be provided to
// specify a different capacity; it must be no smaller than the
// length, so make([]int, 0, 10) allocates a slice of length 0 and
// capacity 10.
// Map: An empty map is allocated with enough space to hold the
// specified number of elements. The size may be omitted, in which case
// a small starting size is allocated.
// Channel: The channel's buffer is initialized with the specified
// buffer capacity. If zero, or the size is omitted, the channel is
// unbuffered.
func make(t Type, size ...IntegerType) Type

上記のコードから、

t## が# make 関数のパラメータは、slice、map、chan のいずれかであり、戻り値もその型そのものです。

Use

以下ではスライスを使用して例を示します:

var s1 []int
if s1 == nil {
    fmt.Printf("s1 is nil --> %#v \n ", s1) // []int(nil)
}

s2 := make([]int, 3)
if s2 == nil {
    fmt.Printf("s2 is nil --> %#v \n ", s2)
} else {
    fmt.Printf("s2 is not nill --> %#v \n ", s2)// []int{0, 0, 0}
}

スライスのゼロ値は

nil

ですが、 make を使用します。 初期化後、スライスの内容は、[]int{0, 0, 0} のように、int 型のゼロ値で埋められます。 map と chan は似ているので、詳細は説明しません。

要約

上記の分析を通じて、new と make の主な違いは次のように要約されます。スライス、マップ、およびチャネル タイプのデータの配布および初期化にのみ使用されます。 new は任意のタイプのデータを割り当てることができます。

    new 割り当ては、タイプ
  • *Type

    であるポインタを返します。 make は型自体を返します (例:

    Type
  • ;
  • new 割り当てられたスペースはクリアされます)。 make がスペースを割り当てた後、初期化されます;

  • 推奨される学習: "
  • ビデオ チュートリアルに進む

    "

以上がGo 言語の new キーワードと make キーワードの違いについて話しましょうの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。