gpt4 book ai didi

function - 高语 : Return 2d slice for any type

转载 作者:IT王子 更新时间:2023-10-29 02:02:36 26 4
gpt4 key购买 nike

我知道如何创建这样的二维 slice 。

var data []int
data = make([]int, w*h)
v := make([][]int, h)
for i := 0; i < h; i++ {
v[i] = data[w*i : w*(i+1)]
}

由于这非常冗长,而且我将创建其中的许多内容,因此我决定将其重构为一个函数。

func create2dSlice(w, h int) [][]int {
var data []int
data = make([]int, w*h)
v := make([][]int, h)
for i := 0; i < h; i++ {
v[i] = data[w*i : w*(i+1)]
}
return v
}

func main() {
a := create2dSlice(3, 2)
}

这只适用于整数。在 golang 中有什么方法可以对重用相同代码的其他类型执行此操作?

我来自 C++,我希望能够做这样的事情。

create2dSlice<int>(w, h)

最佳答案

Go 没有泛型。对于矩阵,类似的问题,我在 snippet 文件夹中的 matrix.go 文件中有一个 NewMatrix 函数。按照设计,我可以简单地复制它并将 []int 全局更改为另一种类型,例如 []float64

您可以通过为 w slice 提供有效容量来改进您的功能。

例如,

package main

import "fmt"

func NewMatrix(r, c int) [][]int {
a := make([]int, c*r)
m := make([][]int, r)
lo, hi := 0, c
for i := range m {
m[i] = a[lo:hi:hi]
lo, hi = hi, hi+c
}
return m
}

func create2dSlice(w, h int) [][]int {
a := make([]int, w*h)
s := make([][]int, h)
lo, hi := 0, w
for i := range s {
s[i] = a[lo:hi:hi]
lo, hi = hi, hi+w
}
return s
}

func main() {
r, c := 2, 3
m := NewMatrix(r, c)
fmt.Println(m)
w, h := c, r
a := create2dSlice(w, h)
fmt.Println(a)
}

输出:

[[0 0 0] [0 0 0]]
[[0 0 0] [0 0 0]]

The Go Programming Language Specification

Slice expressions

Slice expressions construct a substring or slice from a string, array, pointer to array, or slice. There are two variants: a simple form that specifies a low and high bound, and a full form that also specifies a bound on the capacity.

Full slice expressions

For an array, pointer to array, or slice a (but not a string), the primary expression

a[low : high : max]

constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high]. Additionally, it controls the resulting slice's capacity by setting it to max - low.

关于function - 高语 : Return 2d slice for any type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com