I'm a seasoned developer but new to Go. The documentation I have found is not straightforward. I'm used to Java, Scala and Python, but Go is new to me. I'm trying to create a library in Go, and I'm in the first steps of creating the project structure. When I run go build it tells me there are "no Go files in ...". This is a pure library and I don't want a main file. Is there a way to achieve this or is a main file required no matter what?
Finding documentation and looking at sample projects. I do have files and I have run some tests with a main file in place, but as soon as I delete the main file it's when I get a bit lost on how to build it correctly.
It depends a bit on what you mean by "library". If you mean a pre-compiled binary object, like a .a or .so library in C, Go doesn't really have anything like that. Dependent packages are downloaded as source and then compiled into your binary.
If you mean, "a module I can import and use in other projects"...Have you looked to see how other modules are structured? Using e.g. the yaml module as an example, we see:
main.gogo mod tidy; go build the go build command will run without errors.So for example I can create a module mymodule-dep with this structure:
.
├── functions.go
└── go.mod
Where go.mod has:
module github.com/larsks/mymodule-dep
go 1.20
And functions.go has:
package mymodule_dep
import "strings"
func Replace(s string) string {
return strings.Replace(s, "Hello", "Goodbye", -1)
}
I can use that module by importing into another project, like this:
package main
import (
"fmt"
dep "github.com/larsks/mymodule-dep"
)
func main() {
fmt.Println(dep.Replace("Hello, world!"))
}
This assumes that there exists a repository https://github.com/larsks/mymodule-dep (which does exist right now).
If I build the above code, running it produces:
Goodbye, world!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With