dprntkxh703029 2017-05-15 21:10
浏览 235

Golang:这是从另一个Slice的一部分创建Slice的可接受方法吗?

I have searched around and have not found another example of this being done but I inadvertently discovered that I was able to create a slice from a fragment of another slice by simply passing that fragment to a function that accepts a slice and returning that slice.

Example:

   package main

import "fmt"

func makeSliceFrom(s []int) []int {
    return s
}

func main() {
    s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    newS := makeSliceFrom(s[1:7])
    fmt.Println(newS)
}

I am not asking if this works, because I know it works and seems to work well, I am asking if this is supported or has some unforeseen cost that I am not aware of. It seems odd that I have not seen any examples of this being done.

  • 写回答

1条回答 默认 最新

  • dpdhnd3577 2017-05-16 02:14
    关注

    A slice can be created with the built-in function called make, which has the signature,

    func make([]T, len, cap) []T
    

    Recommended Reading :

    https://blog.golang.org/go-slices-usage-and-internals

    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services