为什么Go语言需要使用双引号来声明导入?

huangapple go评论79阅读模式
英文:

Why go requires double quoted import declaration

问题

作为一个Go语言初学者,每当我开始一个新的源文件时,这个问题总是困扰着我。Go语言的包声明定义了包的名称,不需要使用双引号,因为包的名称必须是一个标识符,不能包含无效的字符,比如空格或其他字符。然而,当涉及到导入声明时,包的名称必须使用双引号,因为包的名称正是在包声明中使用的那个,它也必须是一个标识符(当然,/可以作为分隔符)。在我看来,这只会增加更多的按键操作,没有其他好处。我想知道为什么设计成导入必须是双引号字符串。

此外,如果我们看其他语言,比如#include <foo.h>using System.Barimport java.lang.moo,它们都不要求导入是字符串。

英文:

As a go beginner this always gets me whenever I start a new source file. So go's package clause defines the package name, without double quotes, since the package name must be an identifier, it cannot contains invalid chars like space or something. However, when it comes to import declarations, the package name must be double quoted, as the package name is exactly the one used in package clause, it must be identifier too(of course / is allowed as separator). It looks to me that would only add more key strokes without other benefits. I wonder why it is designed this way that imports must be double quoted strings.

Also, if we look at other languages, #include &lt;foo.h&gt;, using System.Bar, import java.lang.moo none of them requires imports to be strings.

答案1

得分: 6

一个路径 a/b/foo 更像是一个字符串而不是一个标识符:标识符没有分隔符,而路径可以包含在标识符中不允许的字符。你说包名不能包含空格,这是正确的,但路径可以包含空格,就像包名不能包含句点(.)一样,但路径可以。例如:

import "golang.org/x/exp/shiny/vendor/github.com/BurntSushi/xgb/render"

这在很大程度上与C语言相似,问题中列出的C语言不使用字符串来指定 #include 路径,但与Go语言的导入语句有相似之处。这两种形式都类似于字符串:#include <a/b/foo.h>#include "a/b/foo.h",尽管其中一种使用 <> 而不是引号来界定字符串。

英文:

A path a/b/foo is more like a string than an identifier: identifiers don't have separators, and paths may contain characters that aren't allowed in identifiers. You say package names can't contain spaces, which is true, but paths can, just as package names can't contain periods (.), but paths can. For example:

import &quot;golang.org/x/exp/shiny/vendor/github.com/BurntSushi/xgb/render&quot;`

This is mostly the same as C, which is listed in the question as not using strings to specify #include paths, but shares similarities with the go import statement. The two forms are both string-like: #include &lt;a/b/foo.h&gt; and #include &quot;a/b/foo.h&quot; although one uses &lt;&gt; rather than quotes to delimit the string.

huangapple
  • 本文由 发表于 2016年4月16日 23:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/36666112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定