英文:
OSX 10.10.2 - cmd start undefined showing
问题
如何修复这个问题?(OSX 10.10.2,go版本go1.4.2 darwin/amd64)
错误:
>cmd.Start未定义(类型string没有Start字段或方法)
代码:
myos := runtime.GOOS;
myarch := runtime.GOARCH;
const url = "http://localhsot:9090"
if myarch == "386" {
cmd := exec.Command("open", "-b" , "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url);
} else {
cmd := exec.Command("open", "-b" , "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url);
}
err := cmd.Start();
if err != nil {
fmt.Println("failed");
}
英文:
How to fix it? (OSX 10.10.2, go version go1.4.2 darwin/amd64)
Error:
>cmd.Start undefined (type string has no field or method Start)
Code:
myos := runtime.GOOS;
myarch := runtime.GOARCH;
const url = "http://localhsot:9090"
if myarch == "386" {
cmd := exec.Command("open", "-b" , "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url);
} else {
cmd := exec.Command("open", "-b" , "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url);
}
err := cmd.Start();
if err != nil {
fmt.Println("failed");
}
答案1
得分: 2
如果你的cmd
变量遮蔽了封闭函数中的cmd
参数(在OP的问题中不可见),那么cmd := exec.Command
将声明一个新的cmd
(短变量声明形式),它在if/else
作用域之外是不可见的。
OP YumYumYum在评论中确认:
> 我有这样的代码:func main() { cmd := "";
这是一个将类型string与cmd
关联的短变量声明。
这与exec.Command() *exec.Cmd
不太匹配,它返回一个*exec.Cmd
。
最好声明一个var cmdopen *exec.Cmd
(不同的名称,以确保安全),并实例化它,以确保cmdopen
是预期类型*exec.Cmd
。
var cmdopen *exec.Cmd
if myarch == "386" {
cmdopen = exec.Command("open", "-b", "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url)
} else {
cmdopen = exec.Command("open", "-b", "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url)
}
err := cmdopen.Start()
(注意在cmdopen = exec.Command
中使用=
而不是:=
)
英文:
If your cmd
variable is shadowing a cmd
parameter in an enclosing function (not visible in the OP's question), then the cmd := exec.Command
would declare a new cmd
(short variable declaration form) which wouldn't be visible outside of the if/else
scope.
The OP YumYumYum confirms in the comments:
> I had this: func main() { cmd := "";
This is a short variable declaration associating the type string to cmd
.
That wouldn't work well with exec.Command() *exec.Cmd
, which returns a *exec.Cmd
.
If would be better to declare a var cmdopen *exec.Cmd
(different name, just to be on the safe side) and instantiates it, in order to be sure that the cmdopen
is from the expected type *exec.Cmd
.
var cmdopen *exec.Cmd
if myarch == "386" {
cmdopen = exec.Command("open", "-b", "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url)
} else {
cmdopen = exec.Command("open", "-b", "com.google.Chrome", "--args", "--chrome-frame", "--kiosk", url)
}
err := cmdopen.Start()
(note the use of '=
' instead of ':=
' in cmdopen = exec.Command
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论