有没有办法获取切片的长度/容量地址?

huangapple go评论121阅读模式
英文:

Is there a way get slice's len/cap address?

问题

我知道有len()cap()函数可以返回切片的长度和容量,但我想要获取切片的地址,以便手动修改它。

英文:

I know there are len() and cap() functions that return len/cap of slice, but I want to get address of slice to modify it by hand.

答案1

得分: -1

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "unsafe"
  6. )
  7. func main() {
  8. // int类型的切片
  9. us := []int{1, 2, 3, 4}
  10. // 长度: 4, 容量: 4
  11. fmt.Printf("长度: %d, 容量: %v\n", len(us), cap(us))
  12. hdr := (*reflect.SliceHeader)(unsafe.Pointer(&us))
  13. hdr.Cap = 10
  14. hdr.Len = 100
  15. // 长度: 100, 容量: 10
  16. fmt.Printf("长度: %d, 容量: %v\n", len(us), cap(us))
  17. }

输出结果:

  1. 长度: 4, 容量: 4
  2. 长度: 100, 容量: 10
英文:
  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "unsafe"
  6. )
  7. func main() {
  8. // slice of int
  9. us := []int{1, 2, 3, 4}
  10. // len: 4, cap: 4
  11. fmt.Printf("len: %d, cap: %v\n", len(us), cap(us))
  12. hdr := (*reflect.SliceHeader)(unsafe.Pointer(&us))
  13. hdr.Cap = 10
  14. hdr.Len = 100
  15. // len: 100, cap: 10
  16. fmt.Printf("len: %d, cap: %v\n", len(us), cap(us))
  17. }

Sample output:

  1. len: 4, cap: 4
  2. len: 100, cap: 10

huangapple
  • 本文由 发表于 2021年5月24日 17:20:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/67669551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定