为什么我不能在Golang中像这样编写Windows文件路径?

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

why cant I write a windows filepath like this in golang ?

问题

我正在尝试在Windows上使用Golang读取文件。路径是C:\Users\lenovo\Downloads\1.jpeg,我写的代码如下:

filepath := "C:\Users\lenovo\Downloads.jpeg"

这个声明和赋值本身是非法的,因为在VSCode中会被标记为红色。我一直在阅读关于Golang如何使用filepath包处理路径问题的资料,但它并没有涵盖\作为分隔符的情况。

顺便说一下,如果在上述语句中的每个\后面添加一个\,它就可以工作了。

英文:

I am trying to read a file on windows in golang. The path is C:\Users\lenovo\Downloads\1.jpeg, and I write like this:

filepath := "C:\Users\lenovo\Downloads\1.jpeg"

This declaration and assignment is illegal by itself as it is marked red in vscode. I've been reading about how golang uses filepath package to handle path issues, but it does not cover the situation where \ is the separator.

By the way, if a \ is added after each \ in the statement above, it works.

答案1

得分: 3

我不使用vscode,但我知道\是一个转义字符。

\U\l\D没有特定的含义。

所以你应该使用以下代码:

filepath := "C:\\Users\\lenovo\\Downloads\.jpeg"
英文:

I don't use vscode but I know \ is an escape character.

And there is no meaning for \U, \l, and \D.

So you should use,

filepath := "C:\\Users\\lenovo\\Downloads\\1.jpeg"

答案2

得分: 3

你可以使用反引号来表示原始字符串,其中没有任何转义字符:

path := `C:\Users\lenovo\Downloads.jpeg`
英文:

Alternatively use backticks for a raw string where nothing is escaped:

path := `C:\Users\lenovo\Downloads.jpeg`

huangapple
  • 本文由 发表于 2022年3月3日 17:43:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/71335005.html
匿名

发表评论

匿名网友

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

确定