« Back to Index

[Golang change function signature without breaking existing consumers]

View original Gist on GitHub

Tags: #go #golang #default #variadic #interface #api

Golang change function signature without breaking existing consumers.go

package main

import (
	"fmt"
)

type Options struct {
	timeout int
}

func foo(opts ...Options) {
    // we're able to provide a default value for the original consumers!
	timeout := 30

	for _, o := range opts {
		timeout = o.timeout
		break
	}

	fmt.Println(timeout)
}

func main() {
    // original code had no args for foo() so consumer shouldn't break.
	foo()
  
    // if more than one arg provided, then it'll be ignored within foo()
	foo(Options{123}, Options{456})
}