"Go append()"의 두 판 사이의 차이

 
(같은 사용자의 중간 판 4개는 보이지 않습니다)
56번째 줄: 56번째 줄:
fruits = append(fruits, newFruits...)
fruits = append(fruits, newFruits...)
fmt.Println(fruits) // [apple banana mango melon]
fmt.Println(fruits) // [apple banana mango melon]
}
</syntaxhighlight>
<syntaxhighlight lang='go' run>
package main
import "fmt"
func merge(a, b []string) []string {
a = append(a, b...)
return a
}
func main() {
a := []string{"apple", "banana"}
b := []string{"mango", "melon"}
c := merge(a, b)
fmt.Println("a=", a) // a= [apple banana]
fmt.Println("b=", b) // b= [mango melon]
fmt.Println("c=", c) // c= [apple banana mango melon]
}
</syntaxhighlight>
<syntaxhighlight lang='go' run>
package main
import "fmt"
func merge(a, b *[]string) {
*a = append(*a, *b...)
}
func main() {
a := []string{"apple", "banana"}
b := []string{"mango", "melon"}
merge(&a, &b)
fmt.Println("a=", a) // a= [apple banana mango melon]
fmt.Println("b=", b) // b= [mango melon]
}
}
</syntaxhighlight>
</syntaxhighlight>


==같이 보기==
==같이 보기==
* [[Go 닐 슬라이스 vs 빈 슬라이스]]
* [[함수 push()]]
* [[함수 push()]]


[[분류: Go 슬라이스]]
[[분류: Go 슬라이스]]

2024년 7월 6일 (토) 19:18 기준 최신판

1 개요[ | ]

Go append()
package main

import "fmt"

func main() {
	var numbers []int
	numbers = append(numbers, 1, 3, 5)
	fmt.Println(numbers) // [1 3 5]
}
package main

import "fmt"

func main() {
	var fruits = []string{"banana", "orange"}
	fruits = append(fruits, "apple", "mango")
	fmt.Println(fruits) // [banana orange apple mango]
}

2 append nil 테스트[ | ]

package main

import "fmt"

func main() {
	var fruits = []string{"lemon", "orange"}
	fmt.Printf("%#v\n", fruits)

	var a []string = []string{}
	fruits = append(fruits, a...)
	fmt.Printf("%#v\n", fruits)

	var b []string = nil
	fruits = append(fruits, b...)
	fmt.Printf("%#v\n", fruits)
}

3 #[ | ]

package main

import "fmt"

func main() {
	fruits := []string{"apple", "banana"}
	newFruits := []string{"mango", "melon"}
	fruits = append(fruits, newFruits...)
	fmt.Println(fruits) // [apple banana mango melon]
}
package main

import "fmt"

func merge(a, b []string) []string {
	a = append(a, b...)
	return a
}

func main() {
	a := []string{"apple", "banana"}
	b := []string{"mango", "melon"}
	c := merge(a, b)
	fmt.Println("a=", a) // a= [apple banana]
	fmt.Println("b=", b) // b= [mango melon]
	fmt.Println("c=", c) // c= [apple banana mango melon]
}
package main

import "fmt"

func merge(a, b *[]string) {
	*a = append(*a, *b...)
}

func main() {
	a := []string{"apple", "banana"}
	b := []string{"mango", "melon"}
	merge(&a, &b)
	fmt.Println("a=", a) // a= [apple banana mango melon]
	fmt.Println("b=", b) // b= [mango melon]
}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}