简单的golang程序无法运行 [英] Simple golang program doesn't run

查看:603
本文介绍了简单的golang程序无法运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的golang脚本T1.go:

package main

import "fmt"

func main() {
    fmt.Println("Hello world")
}

go run T1.go运行它,我得到:

T1.go:1:15: expected ';', found 'import'

如果我在行尾添加了;,则该程序可以运行:

package main;

import "fmt";

func main() {
    fmt.Println("Hello world")
}

但是行号以golang结尾的分号不是多余的吗?

PS:我在64位窗口7上,golang版本为devel +f4d1cb8d9a91 1.2rc1 . 错误代码可在 http://play.golang.org/ <上完美运行/p>

更新我已经使用dos2unix将源代码转换为unix行结尾,但是它没有任何改变

说明我的围棋安装在C:\go目录中,并且C:\go\bin已添加到%PATH%环境变量中;源代码T1.go放在C:\t\go目录中,该目录与go安装目录不同.不确定此配置是否会导致此问题.

解决方案

您的十六进制转储显示您正在使用T1.go文件中的回车符(U + 000D)而不是LineFeeds(U + 000A).在Mac中,仅将CR用作行尾是一种古老的方法.

规范指出,新行是单个换行字符.由于找不到此内容,因此解析器假定所有内容都写在同一行上.在这种情况下,编译器要求您实际键入分号.

解决方案

将您的CR更改为LF,它应该可以工作.

如果使用Notepad ++,则可以在编辑""EOL转换""Unix/OSX格式"菜单中进行此转换.

go fmt不会将CR转换为LF,但是会将CRLF转换为LF.
dos2unix也是如此.就您而言,它应与mac2unix一起使用.

Here is a simple golang script T1.go:

package main

import "fmt"

func main() {
    fmt.Println("Hello world")
}

run it with go run T1.go, I get:

T1.go:1:15: expected ';', found 'import'

If I added ; to line end, the program is okay to run:

package main;

import "fmt";

func main() {
    fmt.Println("Hello world")
}

But isn't the semicolon redundant of line ending in golang?

PS: I am on 64bit window 7, the golang version is devel +f4d1cb8d9a91 or 1.2rc1. The error code runs perfect on http://play.golang.org/

Updates I've used dos2unix to convert the source code to unix line ending, but it doesn't change anything

Notes My go is installed in C:\go directory and the C:\go\bin is added into the %PATH% environment variable; The source code T1.go is put inside the C:\t\go directory, which is different from the go installation directory. Not sure if this configuration contribute to the issue.

解决方案

Your Hex dump shows that you are using Carriage Return characters (U+000D) instead of LineFeeds (U+000A) in the T1.go file. Using only CR as End-of-line is an old Mac way of doing it.

The specification states that a new line is a single line feed character. Since this is not found, the parser assumes it is all written on the same line. In such a case, the compiler requires that you actually type out the semi-colons.

Solution

Change your CR to LF and it should work.

If you use Notepad++, you can do this conversion in the menu Edit - EOL Conversion - Unix/OSX Format.

go fmt does not convert CR to LF, while it does convert CRLF to LF.
The same goes for dos2unix. In your case, it should work with mac2unix.

这篇关于简单的golang程序无法运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆