英文:
How can I run Effective GO source code in my local environment?
问题
我正在学习Go语言,我尝试在我的本地环境(GO 1.18+VS code)中运行Effective GO(https://go.dev/doc/effective_go#multiple-returns)的示例源代码。
例如:
func nextInt(b []byte, i int) (int, int) {
for ; i < len(b) && !isDigit(b[i]); i++ {
}
x := 0
for ; i < len(b) && isDigit(b[i]); i++ {
x = x*10 + int(b[i]) - '0'
}
return x, i
}
for i := 0; i < len(b); {
x, i = nextInt(b, i)
fmt.Println(x)
}
另一个例子:
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := new(File)
f.fd = fd
f.name = name
f.dirinfo = nil
f.nepipe = 0
return f
}
非常感谢提供一些提示!提前谢谢!
英文:
I am beginning learn GO, I try to run the Effective GO (https://go.dev/doc/effective_go#multiple-returns) example source code in my local environment(GO 1.18+VS code).
For example
func nextInt(b []byte, i int) (int, int) {
for ; i < len(b) && !isDigit(b[i]); i++ {
}
x := 0
for ; i < len(b) && isDigit(b[i]); i++ {
x = x*10 + int(b[i]) - '0'
}
return x, i
}
for i := 0; i < len(b); {
x, i = nextInt(b, i)
fmt.Println(x)
}
Another example:
if fd < 0 {
return nil
}
f := new(File)
f.fd = fd
f.name = name
f.dirinfo = nil
f.nepipe = 0
return f
}
Very appreciate give some Tips! Thanks in advance!
答案1
得分: 1
你需要创建一个名为main
的包,并在其中创建一个main
函数。
以下是一个main.go
文件的示例:
package main
import "fmt"
func isDigit(b byte) bool {
// 在这里实现函数...
}
func nextInt(b []byte, i int) (int, int) {
for ; i < len(b) && !isDigit(b[i]); i++ {
}
x := 0
for ; i < len(b) && isDigit(b[i]); i++ {
x = x*10 + int(b[i]) - '0'
}
return x, i
}
func main() {
b := []byte{102, 97, 108, 99, 111, 110}
for i := 0; i < len(b); {
x, i = nextInt(b, i)
fmt.Println(x)
}
}
要执行该程序,请运行:go run main.go
英文:
You need to create a package main and a main function inside of it
Here is an example of a main.go
file
package main
import "fmt"
func isDigit(b byte) bool {
// function implementation here...
}
func nextInt(b []byte, i int) (int, int) {
for ; i < len(b) && !isDigit(b[i]); i++ {
}
x := 0
for ; i < len(b) && isDigit(b[i]); i++ {
x = x*10 + int(b[i]) - '0'
}
return x, i
}
func main() {
b := []byte{102, 97, 108, 99, 111, 110}
for i := 0; i < len(b); {
x, i = nextInt(b, i)
fmt.Println(x)
}
}
To execute run: go run main.go
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论