Standard library / os
os.Chown()
Changes ownership of a named file, following symlinks. On Unix -1 leaves the corresponding ID unchanged; changing ownership may require privileges. Use only a disposable file. Example intended for Linux/AMD64 with Go 1.23.2 in a disposable working directory; other platforms may differ. Expected stdout: 'ok\n'.
Formal Syntax & Structure
go syntaxgo
func Chown(name string, uid, gid int) errorParameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | string | File or executable name, according to the operation. |
| uid | int | User ID; -1 leaves it unchanged on Unix. |
| gid | int | Group ID; -1 leaves it unchanged on Unix. |
Return Value
error
Changes ownership of a named file, following symlinks.
Working Example
Example Snippetgo
package main
import ( "fmt" "os")
func must(e error) { if e != nil { panic(e) }}func temp() *os.File { f, e := os.CreateTemp(".", "fixture-"); must(e); return f }func main() { f := temp() defer os.Remove(f.Name()) defer f.Close() must(os.Chown(f.Name(), -1, -1)) fmt.Println("ok")}