Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a Go Library without a main [closed]

Tags:

go

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.

like image 881
blade Avatar asked Dec 30 '25 15:12

blade


1 Answers

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:

  • There is no main.go
  • If you clone it and run go 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!
like image 174
larsks Avatar answered Jan 02 '26 08:01

larsks