ternary

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2024 License: MIT Imports: 0 Imported by: 13

README

Go ternary

Go Reference

The missing ternary operator for Go.

It's a blazing fast, 7 lines of code package that will save you a lot of lines of code over readability.

Honestly, don't take this package too seriously. It's just a joke to keep me busy one evening.

Installation

go get github.com/julien040/go-ternary

Usage/Examples

import (
    "github.com/julien040/go-ternary"
)

ternary.If(true, "foo", "bar") // "foo"
ternary.If(false, "foo", "bar") // "bar"

// Use it for pluralization
ternary.If(len(slice) > 2, "objects", "object") // "objects"

ternary.If(true, 5.4, 3.2) // 5.4

FAQ

Which type can I use?

Thanks to generics, you can use any type you want.

What is the minimum Go version?

Because of generics, you need at least Go 1.18.

Contributing

Contributions are always welcome!

I accept any contribution, from code to documentation, bug reports, and feature requests.

However, I wonder if there is much to contribute to this project since it's pretty simple.

License

MIT

Authors

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func If

func If[T any](condition bool, a, b T) T

If is the replacement ternary operator in Go

Usage:

ternary.If(condition bool, elementReturnedIfTrue, elementReturnedIfFalse)

Example:

ternary.If(true, "foo", "bar") // returns "foo"
ternary.If(false, "foo", "bar") // returns "bar"

func IfFunc added in v1.0.1

func IfFunc[T any, R any](condition bool, a, b T, f func(T) R) R

IfFunc implements a given function using the chosen element as parameter

Usage:

ternary.If(condition bool, elementPassedIfTrue, elementPassedIfFalse, function func(element))

Example:

ternary.If(true, "foo", "bar", func(e any) {
	return fmt.Sprintf("%v", e)
}) // returns "foo"

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL