英文:
Go multidimensonal array variable assignment and usage for os/exec
问题
我正在尝试在golang中创建一个命令数组,并循环遍历它们。我不确定是否应该使用map还是slice,而且我确定我的语法是错误的。这是我的第一个golang应用程序,我在文档中遇到了困难。找不到我的用例。
问题在于变量的赋值。语法不正确,无法编译。
var c2 = [9][3]string{
[3]string{"/c", "ipconfig", "/all"},
[3]string{"/c", "ipconfig", "/all"},
[3]string{"/c", "arp", "-a"},
[3]string{"/c", "route", "print"},
[2]string{"/c", "set"},
[2]string{"/c", "systeminfo"},
[3]string{"/c", "wmic", "qfe"},
[3]string{"/c", "tasklist", "/svc"},
[3]string{"/c", "query", "user"},
}
for i := 0; i < len(c2); i++ {
x, e := exec.Command("cmd.exe", c2[i][0], c2[i][1], c2[i][2]).Output()
if e != nil {
log.Fatal(e)
}
fmt.Println(string(x))
}
希望这可以帮助到你!
英文:
I am trying to create an array of commands in golang and loop through them. I am not sure if I should use a map or a slice and I am sure my syntax is wrong. This is my first golang app and I am struggling from the docs. Can't find my use case.
The issue is assigning the variables. The syntax is incorrect and will not compile.
var c2[9][...]string{
[3]string{"/c", "ipconfig", "/all"},
[3]string("/c", "ipconfig", "/all"),
[3]string("/c", "arp", "-a"),
[3]string("/c", "route", "print"),
[2]string("/c", "set"),
[2]string("/c", "systeminfo"),
[3]string("/c", "wmic", "qfe"),
[3]string("/c", "tasklist", "/svc"),
[3]string("/c", "query", "user"),
}
for i := range len(c2) { //assign
x, e := exec.Command("cmd.exe", c2[i][0], c2[i][1], c2[i][2]).Output()
if e != nil {
log.Fatal(e)
}
fmt.Println(string(x))
}
答案1
得分: 4
使用切片代替固定长度数组:
var c2 = [][]string{
{"/c", "ipconfig", "/all"},
{"/c", "ipconfig", "/all"},
{"/c", "arp", "-a"},
{"/c", "route", "print"},
{"/c", "set"},
{"/c", "systeminfo"},
{"/c", "wmic", "qfe"},
{"/c", "tasklist", "/svc"},
{"/c", "query", "user"},
}
然后运行你的命令:
for i := range c2 {
x, e := exec.Command("cmd.exe", c2[i]...).Output()
if e != nil {
log.Fatal(e)
}
fmt.Println(string(x))
}
英文:
Instead of using fixed-length arrays, use slices:
var c2 = [][]string{
{"/c", "ipconfig", "/all"},
{"/c", "ipconfig", "/all"},
{"/c", "arp", "-a"},
{"/c", "route", "print"},
{"/c", "set"},
{"/c", "systeminfo"},
{"/c", "wmic", "qfe"},
{"/c", "tasklist", "/svc"},
{"/c", "query", "user"},
}
Then, run your commands:
for i := range len(c2) { //assign
x, e := exec.Command("cmd.exe", c2[i]...).Output()
if e != nil {
log.Fatal(e)
}
fmt.Println(string(x))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论