Go語言學習查缺補漏ing Day2

恆生LIGHT雲社群發表於2021-12-03

作者:ReganYue

來源: 恆生LIGHT雲社群

Go語言學習查缺補漏ing Day2

一、函式返回引數命名的一個注意事項

請大家觀察下面這個函式有什麼問題嗎?

func fun(x, y int) (s int, error) {

  return x * y, nil
}

雖然這個錯誤,在整合開發環境Goland中會有提示,但是其他的開發工具,比如VS Code就不知道會不會提示了。

image-20211120152703592

我們可以看到這個提示:函式有命名的返回引數,也有沒有命名的返回引數。

這就說明函式有多個返回值引數時,如果你給一個引數命了名,那麼其他引數也必須命名。而且如果給引數命名,那麼必須給引數加上括號,無論引數個數是一個還是多個。這裡給第一個引數命名為s,而沒有給第二個引數命名,所以有錯誤。

二、new()和make()有什麼不同?

在Go SDK中,對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

它是一個用於分配記憶體的內建函式,只有一個引數。如果使用這個函式,那麼就會返回一個指向一塊新開闢記憶體的指標,這塊記憶體是第一個參數列示的型別的零值。

我們再來看一看make:

// 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. For example, make([]int, 0, 10) allocates an underlying array
// of size 10 and returns a slice of length 0 and capacity 10 that is
// backed by this underlying array.
// 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

我們可以瞭解,make也是分配記憶體的,但是隻能給slice, map 或者 chan分配記憶體。而且這個make也不返回指標,而是返回你第一個引數代表的型別的值。

經過上面的介紹,我們再來看一看這段程式碼能否通過編譯。




import "fmt"

func main() {
  l := new([]int)
  l = append(l, 0)
  fmt.Println(l)
}

顯然是不能的,下面是報錯資訊:

image-20211120154559775

我們前面講了,new函式new出來的是指標,而指標是不能進行append操作的。所以我們建立slice, map 或者 chan最好使用make函式,而不要使用new函式。

三、切片追加切片問題

** 如果有兩個切片,如何使用append把它們拼湊在一個切片裡面呢?**

這樣行不行?

package main


import "fmt"

func main() {
  slice := []int{8, 8, 8}
  append_slice := []int{2, 8}
  slice = append(slice, append_slice)
  fmt.Println(slice)
}

看一看Goland怎麼提示的吧。

image-20211120155228653

好像是不行吧。

這時我們就要使用 ... 這種語法糖。

它有多個功能,其中的一個功能就是可以把切片打散進行傳遞。還有就是在定義函式時使用,可以接收任意個引數。

下面是執行結果:

image-20211120155606933

四、簡短模式宣告變數的限制

我們來看一看下面這一段程式碼,你覺得有沒有什麼問題?

package main


import "fmt"


var(
  two = 200
)
one := 100

func main() {
  fmt.Println(one,two)
}

是有問題的。

就得來談一談變數的簡短模式宣告有哪些限制:

  1. 必須使用顯示初始化,也就是手工給予初值。

  2. 不能指定資料型別,編譯器會根據你指定的初值自動推理變數的型別。

  3. 只能在函式內部使用簡短模式來宣告變數。

我們這裡出現錯誤的原因就是觸發了上述第三點限制:未在函式內部使用簡短模式來宣告變數。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/70001864/viewspace-2845573/,如需轉載,請註明出處,否則將追究法律責任。

相關文章