英文:
How to create unfixed length slice in Go
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是Go语言的新手,有两个问题:
- 假设我们有一个简单的C# for循环:
static void Main(string[] args)
{
List<int> list = new List<int>();
for (int i = 1; i < 10000; i++)
{
if (i % 5 == 0 && i % 3 == 0)
{
list.Add(i);
}
}
foreach (int prime in list)
{
System.Console.WriteLine(prime);
}
Console.ReadKey();
}
如果我想在Go中实现相同的功能,我需要使用切片(slices)。但是如何做到这一点?
- 在变量声明中,更常用的是哪种形式:
短形式(s := 3)
还是
长形式(var s int = 3)?
英文:
I'm new in Go and I have 2 questions:
1 Let's say we have simple for loop written in C#:
static void Main(string[] args)
{
List<int> list = new List<int>();
for (int i = 1; i < 10000; i++)
{
if (i % 5 == 0 && i % 3 == 0)
{
list.Add(i);
}
}
foreach (int prime in list)
{
System.Console.WriteLine(prime);
}
Console.ReadKey();
}
If I wanted to do the same in Go I'll have to use slices. But how to do that?
- Which of variable declaration form is more often used:
short form (s:= 3)
or
long (var s int = 3)?
答案1
得分: 3
在Go语言中,数组有它们的用处,但它们有点不灵活,所以在Go代码中并不经常看到它们。切片(slice)则无处不在。它们建立在数组的基础上,提供了强大的功能和便利性。
切片(slice)的长度不是固定的,它是灵活的。
你可以按照以下方式声明一个空的切片:
list := make([]int, 0)
list := []int{}
var list []int
以下是用Go语言编写上述函数的示例代码:
package main
import (
"fmt"
)
func main() {
var list []int
for i := 0; i < 10000; i++ {
if i%5 == 0 && i%3 == 0 {
list = append(list, i)
}
}
for _, val := range list {
fmt.Println(val)
}
}
你可以点击这里查看示例代码的运行结果。
英文:
In Go arrays have their place, but they're a bit inflexible, so you don't see them too often in Go code. Slices, though, are everywhere . They build on arrays to provide great power and convenience.
Slice is not of fixed length. It is flexible .
You may declare an empty slice as following
list := make([]int, 0)
list := []int{}
var list []int
Here is how you may right the above function in go
package main
import (
"fmt"
)
func main() {
var list []int
for i:=0;i<10000;i++ {
if i %5 == 0 && i % 3 == 0 {
list = append(list, i)
}
}
for _, val := range list {
fmt.Println(val)
}
}
Here is the play link play
答案2
得分: 2
-
使用以下代码创建一个切片:
list := make([]int, 0)
使用以下代码向切片追加元素:
list = append(list, i)
- 我认为对于你的第二个问题,没有一个单一的答案。这取决于变量在何处以及如何使用。
英文:
-
Create a slice with:
list := make([]int, 0)
Append to a slice with:
list = append(list, i)
- I think there is no single answer to your second question. It depends on how and where the variable is used.
答案3
得分: 0
对于2)
var foo int = 3 // 我想要一个整数变量
bar := foo // bar 将和 foo 具有相同的类型
英文:
For 2)
var foo int = 3 // I want a int variable
bar := foo // bar will be the same type with foo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论