// sample-unix.go: a file with a build constraint. // Free sample from 99helpers.com/file-types/go // // The //go:build line below must come before the package clause, with only // blank lines and comments above it. This file is compiled only for Unix-like // targets (Linux, macOS, the BSDs and others), because it uses // syscall.Getrlimit, which Windows doesn't have. // // Build constraints apply to packages, so try it inside a module: // // mkdir unixdemo && cd unixdemo (and put this file in it) // go mod init example.com/unixdemo // go run . on Linux or macOS: prints the limits // GOOS=windows go build . "build constraints exclude all Go files" // // Naming the file instead (go run sample-unix.go) ignores build constraints, // so on Windows that fails with "undefined: syscall.Rlimit" instead. // // A file name can carry a constraint too: a file named sample_linux.go is // only compiled for Linux, sample_windows_amd64.go only for 64-bit Windows. // The "unix" constraint has no file-name form; it only works in //go:build. //go:build unix package main import ( "fmt" "runtime" "syscall" ) func main() { var limit syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil { fmt.Println("getrlimit:", err) return } fmt.Printf("Built for %s/%s\n", runtime.GOOS, runtime.GOARCH) fmt.Printf("Open files allowed: %d (soft limit), %d (hard limit)\n", limit.Cur, limit.Max) }