乐闻世界logo
搜索文章和话题

What is the default value of a variable in Go?

1个答案

1

In Go, when variables are declared without explicit initialization, they are assigned default values, which are also known as zero values. Different types of variables have different zero values:

  • Integer types (int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64) have a zero value of 0.
  • Floating-point types (float32, float64) also have a zero value of 0.
  • Boolean types (bool) have a zero value of false.
  • String types (string) have a zero value of the empty string "".
  • For pointer types, the zero value is nil.
  • Slice, map, and channel types also have a zero value of nil.
  • For arrays, each element is initialized to the zero value of its element type.
  • For structs, each field is initialized to the zero value of its field type.

For example, if we declare the following variables:

go
var a int var b float64 var c bool var d string var e *int

In this example, variables a and b default to 0, c defaults to false, d defaults to the empty string "", and e defaults to nil. These default values ensure that variables have a well-defined state before use, helping to reduce errors such as nil pointers or uninitialized values in the program.

2024年8月7日 21:47 回复

你的答案