英文:
Why go requires double quoted import declaration
问题
作为一个Go语言初学者,每当我开始一个新的源文件时,这个问题总是困扰着我。Go语言的包声明定义了包的名称,不需要使用双引号,因为包的名称必须是一个标识符,不能包含无效的字符,比如空格或其他字符。然而,当涉及到导入声明时,包的名称必须使用双引号,因为包的名称正是在包声明中使用的那个,它也必须是一个标识符(当然,/可以作为分隔符)。在我看来,这只会增加更多的按键操作,没有其他好处。我想知道为什么设计成导入必须是双引号字符串。
此外,如果我们看其他语言,比如#include <foo.h>
,using System.Bar
,import 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 <foo.h>
, 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 "golang.org/x/exp/shiny/vendor/github.com/BurntSushi/xgb/render"`
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 <a/b/foo.h>
and #include "a/b/foo.h"
although one uses <>
rather than quotes to delimit the string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论