Skip to content

Instantly share code, notes, and snippets.

@heiwa4126
Created January 26, 2023 01:47
Show Gist options
  • Save heiwa4126/9c52bbfbd5964a4bbdd2fea2d189aecd to your computer and use it in GitHub Desktop.
Save heiwa4126/9c52bbfbd5964a4bbdd2fea2d189aecd to your computer and use it in GitHub Desktop.
ChatGPTに 「Go言語で配列を逆にする関数を書いてください」と聞いて出てきたコードはコンパイルできなかった
package main
import "fmt"
// ChatGPTに
// 「Go言語で配列を逆にする関数を書いてください」(この例ではスライスだけど)
// と聞いて出てきたコードはコンパイルできなかった。
// - 出力のとこを変えた
// - gerenicsにしてみた (go 1.8以上)
func reverse[T interface{}](s []T) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func main() {
a := []int{1, 2, 3, 4, 5}
fmt.Printf("%#v\n", a)
reverse(a)
fmt.Printf("%#v\n", a)
b := []string{"apple", "banana", "cherry"}
fmt.Printf("%#v\n", b)
reverse(b)
fmt.Printf("%#v\n", b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment