How can I run Effective GO source code in my local environment?

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

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 &lt; len(b) &amp;&amp; !isDigit(b[i]); i++ {
    }
    x := 0
    for ; i &lt; len(b) &amp;&amp; isDigit(b[i]); i++ {
        x = x*10 + int(b[i]) - &#39;0&#39;
    }
    return x, i
}

for i := 0; i &lt; len(b); {
        x, i = nextInt(b, i)
        fmt.Println(x)
    } 

Another example:

    if fd &lt; 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 &quot;fmt&quot;

func isDigit(b byte) bool {
  // function implementation here...
}

func nextInt(b []byte, i int) (int, int) {
    for ; i &lt; len(b) &amp;&amp; !isDigit(b[i]); i++ {
    }
    x := 0
    for ; i &lt; len(b) &amp;&amp; isDigit(b[i]); i++ {
        x = x*10 + int(b[i]) - &#39;0&#39;
    }
    return x, i
}


func main() {
    b := []byte{102, 97, 108, 99, 111, 110}
    for i := 0; i &lt; len(b); {
        x, i = nextInt(b, i)
        fmt.Println(x)
    } 
}

To execute run: go run main.go

huangapple
  • 本文由 发表于 2022年5月16日 09:02:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/72253257.html
匿名

发表评论

匿名网友

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

确定