Skip to content

sfmunoz/golang-playground

Repository files navigation

Golang playground

This repository holds Go snippets created while I'm recalling and learning the language

TL;DR

$ git clone https://github.com/sfmunoz/golang-playground.git

$ cd golang-playground

$ go run main.go
golang playground

Usage:

  $ go run main.go [example-id-or-number]

Examples:

  $ go run main.go c_call
  $ go run main.go 1

Available examples:

  1: c_call .......... call C code from Go
  2: concurrency ..... concurrency
  3: ctx ............. context
  4: http_json ....... HTTP/JSON client/server
  5: make_vs_new ..... make vs new
  6: pointers_refs ... pointers and references
  7: reflection ...... reflection
  8: structs_ints .... structures and interfaces
  9: structs_tags .... structures and tags
 10: templates ....... templates

Reference:

  https://github.com/sfmunoz/golang-playground/

References

Packages vs Modules

From How to Write Go Code:

  • Package:
    • Go programs are organized into packages.
    • A package is a collection of source files in the same directory that are compiled together.
    • Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package.
  • Module:
    • A repository contains one or more modules.
    • A module is a collection of related Go packages that are released together.
    • A Go repository typically contains only one module, located at the root of the repository.
    • A file named go.mod there declares the module path: the import path prefix for all packages within the module

Adapted example from Tutorial: Create a Go module:

$ pwd
<HOME>/go/src/example.com

$ mkdir greetings

$ cd greetings

$ go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings

$ ls
go.mod

$ cat go.mod
module example.com/greetings
go 1.21.2

$ vi greetings.go

$ cat greetings.go
package greetings
import "fmt"
func Hello(name string) string {
    return fmt.Sprintf("Hi, %v. Welcome!", name)
}

$ vi greetings_test.go 

$ cat greetings_test.go
package greetings
import (
    "fmt"
    "testing"
)
func TestHello(t *testing.T) {
    got := Hello("World")
    want := "Hi, World. Welcome!"
    if got != want {
        t.Errorf("got != want | '%s' != '%s'", got, want)
    }
    fmt.Printf("ok: got == want == '%s'\n", got)
}

$ go test
ok: got == want == 'Hi, World. Welcome!'
PASS
ok      example.com/greetings   0.002s

go.mod local module: require + replace

module github.com/user/app

go 1.24.1

require (
	(...)
	test.com/pkg1 v0.0.0-00010101000000-000000000000
)

replace test.com/pkg1 => ../pkg1

Core

About

Golang playground

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages