Skip to content

Commit 9bf228c

Browse files
authored
Merge pull request #543 from devlights/add-three-index-slice-example
2 parents c337229 + eac31d6 commit 9bf228c

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

examples/basic/slices/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
2828
m["slice_remove_all_elements"] = RemoveAllElements
2929
m["slice_keep_allocated_memory"] = KeepAllocatedMemory
3030
m["slice_nil_append"] = NilAppend
31+
m["slice_three_index"] = ThreeIndex
3132
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package slices
2+
3+
import "github.com/devlights/gomy/output"
4+
5+
// ThreeIndex は、スライスにて3つのインデックス指定をした場合のサンプルです.
6+
//
7+
// Three-index slices の仕様は、 Go 1.2 にて導入されたもの。
8+
// 3つ目のインデックス指定は、capacity の量を意図的に調整するためにある。
9+
//
10+
// REFERENCES
11+
// - https://stackoverflow.com/questions/27938177/golang-slice-slicing-a-slice-with-sliceabc
12+
// - https://stackoverflow.com/questions/12768744/re-slicing-slices-in-golang/18911267#18911267
13+
// - https://tip.golang.org/doc/go1.2#three_index
14+
// - https://go.dev/ref/spec#Slice_expressions
15+
func ThreeIndex() error {
16+
var (
17+
s = []string{
18+
"golang",
19+
"dotnet",
20+
"java",
21+
"python",
22+
"ruby",
23+
}
24+
s2 = s[1:3]
25+
s3 = s[1:3:4]
26+
)
27+
28+
output.Stdoutf("[s ]", "slice=%v\tlen=%v\tcap=%v\n", s, len(s), cap(s))
29+
output.StdoutHr()
30+
31+
output.Stdoutl("[len(s2)]", "len => high(2nd) - low(1st) => 3 - 1 => 2")
32+
output.Stdoutl("[cap(s2)]", "cap => max(3rd) - low(1st) => len(s) - 1 => 5 - 1 => 4")
33+
output.Stdoutf("[s2 ]", "slice=%v\tlen=%v\tcap=%v\n", s2, len(s2), cap(s2))
34+
35+
output.StdoutHr()
36+
37+
output.Stdoutl("[len(s3)]", "len => high(2nd) - low(1st) => 3 - 1 => 2")
38+
output.Stdoutl("[cap(s3)]", "cap => max(3rd) - low(1st) => 4 - 1 => 3")
39+
output.Stdoutf("[s3 ]", "slice=%v\tlen=%v\tcap=%v\n", s3, len(s3), cap(s3))
40+
41+
return nil
42+
}

0 commit comments

Comments
 (0)