Golang 筆記
  • Introduction
  • 安裝Golang
    • 本地編譯與安裝第三方套件
    • 第一個 GO 程式
    • export 與 import
    • 使用 go mod
  • 基本工具
  • DataBase操作
    • MySQL
    • 使用 ORM
    • MongoDB
  • 基本語法
    • Variable
    • BSON
    • JSON
    • 時間相關
    • Interface
    • Error
    • 型別
    • 字串
    • defer
    • panic, recover
    • Channel 與Goroutine
      • 讀寫鎖
      • for select 與 for range
      • UnBuffered channel 與 Buffered channel
    • Function
    • pointer
    • regExp
    • fmt
    • Make vs New
    • struct
    • Array, Slice 陣列
    • map
  • 核心模組
    • Reflect
    • File
    • Signal
    • BuiltIn
    • Sync
    • IO
    • Sort
    • http
    • crypto
    • context
  • 第三方模組
    • Dom Parser
    • gin 框架
    • Websocket
    • Iris框架
      • 讀取 Body 資料
      • 相關範例
    • Fiber 框架
    • 自動重啟 server 工具
    • go-jwt
  • 測試
  • 原始碼解析
  • 常見問題
    • 資料存取不正確
    • Data races
Powered by GitBook
On this page
  • Array 宣告方法
  • 巢狀陣列
  • 建立 slice
  • 不指定型態
  • Assign any slice to an []interface{}
  • slice 中取值
  • 有關 slice 或 array 當成參數時

Was this helpful?

  1. 基本語法

Array, Slice 陣列

有宣告固定長度為 Array,沒宣告固定長度則為 Slice

Array 宣告方法

當 [] 內有指定長度或使用 ... 則會是 array

arr2 := [5]int{1, 2, 3}
arr3 := [...]int{1, 2, 3, 4, 5}

或

var scores [10]int
scores[0] = 90
scores[1] = 89

巢狀陣列

arr1 := [2][3]int{[3]int{1, 2, 3}, [3]int{4, 5, 6}}
fmt.Println(arr1) // [[1 2 3] [4 5 6]]

建立 slice

不初始長度的array及為 slice

langs := []string{"Go", "Python", "Ruby", "PHP"}

合併 slice

package main

import (
	"fmt"
)

func main() {
	low := []string{"1", "2", "3"}
	high := []string{"11", "22", "33"}
	c := append(low, high...)
	fmt.Println(c)
}

不指定型態

	var cc []interface{}

	fmt.Println(append(cc, 123, "345"))

Assign any slice to an []interface{}

slice 中取值

a[2:]  // same as a[2 : len(a)]
a[:3]  // same as a[0 : 3]
a[:]   // same as a[0 : len(a)]
If a is a pointer to an array, a[low : high] is shorthand for (*a)[low : high].

有關 slice 或 array 當成參數時

slice 如果當參數傳遞不傳 pointer 的話仍會改變原先的變數,但 array 不會改變到原先的變數。

更詳細的說明可參考:

PreviousstructNextmap

Last updated 3 years ago

Was this helpful?

https://stackoverflow.com/questions/39993688/are-slices-passed-by-value
InterfaceSlice · golang/go WikiGitHub
The Go Programming Language Specification - The Go Programming Language
Logo
[Golang] slice 作為參數傳入 func 的注意事項比利。風箏雲。後端工程師
Logo
Logo