Go-可變參數

可變參數

一、使用場景

  • 避免創建僅作傳入參數用的臨時切片
  • 當參數數量未知
  • 傳達你希望增加可讀性的意圖

func test(items ...string){}
func test1(items ...string){}

func main(){
  a:=getA()
  b:=getB()

  //可變參數
  test(a,b)
  //切片參數略顯累贅
  test([]string{a,b})
}


二、傳參不同,函數處理方式不同

例:

func test(items ...string){}

上面是一個可變參數的函數

1. test()
2. test("2","3")
3. items:=[]string{"2","3"}
4. test(items...)
  • 1.不傳參數

    test(),不傳參數,函數內部則的item將會獲得一個nil值

  • 2.傳多個參數

    test(“2”,“3”),傳入多個參數,函數會新建一個切片

    此時items=[]string{“2”,“3”}

  • 3.傳入已有切片

    test(items…),傳入已有切片時,函數會直接使用這個切片,不會新建

    func test(items ...string){
      items[0]=""
    }
    
    items:=[]string{"2","3"}
    test(items...) //items=["","3"]
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章