Skip to content

Commit 89bd124

Browse files
committed
Add unsafes/unsafe_slice.go
1 parent 61ae027 commit 89bd124

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

examples/basic/unsafes/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
1818
m["unsafe_stringdata"] = UnsafeStringData
1919
m["unsafe_pointer_cast"] = PointerCast
2020
m["unsafe_add"] = Add
21+
m["unsafe_slice"] = Slice
2122
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package unsafes
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
"unsafe"
7+
)
8+
9+
// Slice は、unsafe.SliceData() と unsafe.Slice() のサンプルです。
10+
//
11+
// unsafe.SliceData() は、特定のスライスを *T に変換する関数。
12+
// 逆を行ってくれるのが unsafe.Slice() となる。
13+
//
14+
// REFERENCES:
15+
// - https://pkg.go.dev/unsafe@go1.25.3#SliceData
16+
func Slice() error {
17+
var (
18+
original = []byte("helloworld")
19+
result []byte
20+
ptr *byte
21+
)
22+
ptr = unsafe.SliceData(original) // []byteを*byteに変換
23+
result = unsafe.Slice(ptr, len(original)) // *byteを[]byteに変換
24+
25+
fmt.Printf("b1 equals b2: %v\n", bytes.Equal(original, result))
26+
27+
return nil
28+
}

0 commit comments

Comments
 (0)