まず者に説明してみましょう:
result := make([]string, 0, 4)
make組み込み関数は、割り当てと初期化[]string
のオブジェクトは、Slice
のstring
Slice internals:
A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).
のでresult := make([]string, 0, 4)
割り当て、length = 0
とcapacity = 4
とタイプ[]string
のオブジェクトを初期化します。
result := make([]string, 4, 4)
は、タイプ[]string
のオブジェクトをlength = 4
とcapacity = 4
で割り振り、初期化します。これはresult := make([]string, 4)
に等しくなります。ランタイムエラー:範囲外のインデックスresult := make([]string, 0, 4)
このスライスの下にある配列パニックになるresult[0]
を使用して空の意味があると
:
は今result := make([]string, 0, 4)
とresult := make([]string, 4)
の違いは何です。
result := make([]string, 4)
と、このスライスはresult[0]
を用い意味4つのstring
要素、result[1]
、result[2]
、result[3]
がOKである持っているの基礎となる配列:
package main
import "fmt"
func main() {
result := make([]string, 4)
fmt.Printf("%q, %q, %q, %q \n", result[0], result[1], result[2], result[3])
}
を出力:
"", "", "", ""
そしてresult := make([]string, 4)
がに等しいですresult := []string{"", "", "", ""}
このコードの意味:
(
The Go Playground
result := make([]string, 0, 4)
後
"", "", "", ""
The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:
slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)
As a special case, it is legal to append a string to a byte slice, like this:
slice = append([]byte("hello "), "world"...)
機能
myFunc
内部コードで今すぐ
は、あなたがこの作業コードのように、append
を使用することがあります:3210
package main
import "fmt"
func main() {
result := []string{"", "", "", ""}
fmt.Printf("%q, %q, %q, %q \n", result[0], result[1], result[2], result[3])
}
出力は、上記のコードと同じです):
package main
import (
"fmt"
"strings"
)
func main() {
strs := strings.Fields("Political srt")
fmt.Println(len(strs)) // It's not empty so why index out of range
fmt.Println(strs, strs[0], strs[1])
fmt.Println(strings.ContainsAny(strs[0], "eaiuo"))
fmt.Println(myFunc("Political srt"))
}
func myFunc(input string) []string {
strs := strings.Fields(input)
result := make([]string, 0, 4)
for i := 0; i < len(strs); i++ {
if strings.ContainsAny(strs[i], "eaiu") {
result = append(result, strs[i])
} else {
result = append(result, strs[i])
}
}
return result
}
あなたは、この作業コード(The Go Playground)のように、そのコードを簡素化することがあります。aswerため
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(myFunc("Political srt"))
}
func myFunc(input string) []string {
strs := strings.Fields(input)
result := make([]string, 0, 4)
for _, s := range strs {
if strings.ContainsAny(s, "eaiu") {
result = append(result, s)
}
}
return result
}
アスワンに感謝します!スライスについて知りませんでした – jiji