2023-03-22 05:57PM
题目:
实现这样的方法: 可以动态创建一个二维Array, 内容如下
generate_array(3)
获得:
[
[ha],
[ha,ha],
[ha,ha,ha],
]
再如:
generate_array(4)
获得:
[
[Anna],
[Anna,Anna],
[Anna,Anna, Anna],
[Anna,Anna, Anna,Anna],
]
代码1(带日志):
package main
import (
"fmt"
)
func generate_small_array(n int, name string) []string{
// 第一次循环
result := []string{}
for i := 1; i <= n; i++{
result = append(result, name)
fmt.Println("====== 每个循环1, i:", i, "result", result)
}
fmt.Println(result)
return result
}
func main() {
// 第二次循环
result := [][]string{}
for i := 1; i <= 3; i++{
result = append(result, generate_small_array(i, "haha"))
fmt.Println("====== 每个循环2, i:", i, "result", result)
}
fmt.Println(result)
}
结果:
====== 每个循环1, i: 1 result [haha]
[haha]
====== 每个循环2, i: 1 result [[haha]]
====== 每个循环1, i: 1 result [haha]
====== 每个循环1, i: 2 result [haha haha]
[haha haha]
====== 每个循环2, i: 2 result [[haha] [haha haha]]
====== 每个循环1, i: 1 result [haha]
====== 每个循环1, i: 2 result [haha haha]
====== 每个循环1, i: 3 result [haha haha haha]
[haha haha haha]
====== 每个循环2, i: 3 result [[haha] [haha haha] [haha haha haha]]
[[haha] [haha haha] [haha haha haha]]
代码2:
package main
import "fmt"
func sort_array(m int, n string) []string{
var name = []string{}
for i := 1; i <= m; i++{
name = append(name, n)
fmt.Println("name:", name)
}
fmt.Println(name)
return name
}
func main() {
var name = [][]string{}
for i := 1; i <= 3; i++{
name = append(name, sort_array(i,"Anna"))
fmt.Println("i:", i,"name1:", name)
}
fmt.Println("name2:", name)
}
结果:
name: [Anna]
[Anna]
i: 1 name1: [[Anna]]
name: [Anna]
name: [Anna Anna]
[Anna Anna]
i: 2 name1: [[Anna] [Anna Anna]]
name: [Anna]
name: [Anna Anna]
name: [Anna Anna Anna]
[Anna Anna Anna]
i: 3 name1: [[Anna] [Anna Anna] [Anna Anna Anna]]
name2: [[Anna] [Anna Anna] [Anna Anna Anna]]
登录
请登录后再发表评论。
评论列表:
目前还没有人发表评论