Standard library / os

os.MkdirTemp()

Creates a uniquely named temporary directory; caller must remove it. Empty parent uses TempDir. Example uses a disposable temporary workspace. Expected stdout: 'true true\n'.

Formal Syntax & Structure

go syntaxgo
func MkdirTemp(dir, pattern string) (string, error)

Parameters & Attributes

NameTypeDescription
dirstringDirectory pathname.
patternstringShell-style matching pattern.

Return Value

(string, error)

Creates a uniquely named temporary directory; caller must remove it.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os"  "path/filepath"  "strings")
func check(e error) {  if e != nil {    panic(e)  }}func workspace() func() {  root, e := os.MkdirTemp("", "bytemind-go-")  check(e)  old, e := os.Getwd()  check(e)  check(os.Chdir(root))  return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() {  defer workspace()()  d, e := os.MkdirTemp(".", "lab-*")  check(e)  defer os.RemoveAll(d)  i, e := os.Stat(d)  check(e)  fmt.Println(i.IsDir(), strings.HasPrefix(filepath.Base(d), "lab-"))}
Go Reference