tern

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 1 Imported by: 0

README

golang-tern-expression logo

golang-tern-expression

simple tern expression condition ? expression 1 : expression 2 in golang


GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

tern

Lightweight and adaptable Go package for streamlined condition-based logic with elegant tern expressions.


CHINESE README

中文说明

Main Features

🎯 Generic Tern Operations: Type-safe condition-based expressions with comprehensive generic support
Deferred Evaluation: Deferred execution with function-based parameters to optimize performance
🔄 Adaptable Conditions: Support for both boolean and function-based condition-based evaluation
🌍 Zero-Value Handling: Auto zero-value fallbacks and dedicated zero-value comparison utilities
📋 Multiple Evaluation Modes: Direct values, functions, and zero-value aware operations

Installation

go get github.com/yylego/tern

Quick Start

Basic Tern Operations

This example demonstrates the core tern expression features with different evaluation modes.

package main

import (
	"fmt"
	"github.com/yylego/tern"
)

func main() {
	// Basic condition-based selection
	result := tern.BVV(true, "Option A", "Option B")
	fmt.Println(result) // Output: Option A

	// Deferred execution for fallback value
	result = tern.BVF(false, "Default", func() string { return "Computed Fallback" })
	fmt.Println(result) // Output: Computed Fallback

	// Handling zero values as fallback
	result = tern.BV(false, "Fallback")
	fmt.Println(result) // Output: (blank string)
}

⬆️ Source: Source

Zero-Value Comparison

The zerotern subpackage provides utilities for zero-value aware condition-based logic.

package main

import (
	"fmt"
	"github.com/yylego/tern/zerotern"
)

func main() {
	// Direct zero-value comparison
	result := zerotern.VV("non-zero", "fallback")
	fmt.Println(result) // Output: non-zero

	// Function-based fallback for zero values
	result = zerotern.VF("", func() string { return "fallback func" })
	fmt.Println(result) // Output: fallback func
}

⬆️ Source: Source

Safe Slice Access

Safely access slice elements without risking a panic.

package main

import (
	"fmt"
	"github.com/yylego/tern/slicetern"
)

func main() {
	slice := []string{"a", "b", "c"}

	// Get the first element
	first := slicetern.V0(slice)
	fmt.Println(first) // Output: a

	// Get an element by index
	second := slicetern.VX(slice, 1)
	fmt.Println(second) // Output: b

	// Access an out-of-bounds index safely
	safeAccess := slicetern.VX(slice, 5)
	fmt.Println(safeAccess) // Output: (blank string)

	// Access an empty slice safely
	emptySlice := []int{}
	safeFirst := slicetern.V0(emptySlice)
	fmt.Println(safeFirst) // Output: 0
}

⬆️ Source: Source

Function Overview

The tern package provides comprehensive condition-based evaluation functions:

Core Tern Functions
Function Condition Type Main Value Fallback Value
BVV bool Direct value Direct value
BVF bool Direct value Function returning value
BFV bool Function returning value Direct value
BFF bool Function returning value Function returning value
FVV func() bool Direct value Direct value
FVF func() bool Direct value Function returning value
FFV func() bool Function returning value Direct value
FFF func() bool Function returning value Function returning value
Zero-Value Fallback Functions
Function Condition Type Main Value Fallback Value
BV bool Direct value Zero value of type T
BF bool Function returning value Zero value of type T
FV func() bool Direct value Zero value of type T
FF func() bool Function returning value Zero value of type T
Slice Accessor Functions (slicetern)

Functions for safe access to slice elements.

Function Description
V0 Returns the first element of a slice, or the zero value if the slice is blank.
VX Returns the element at a given index, or the zero value if out of bounds.

Advanced Usage

Deferred Evaluation Benefits

Performance optimization through deferred execution:

func expensiveComputation() string {
	fmt.Println("Computing...")
	return "Complex Result"
}

result := tern.BVF(false, "Default", expensiveComputation)
// Output: Default (expensiveComputation is not executed)
Working with Zero Values

Get zero value for all generic types:

fmt.Println(tern.Zero[int]()) // Output: 0
fmt.Println(tern.Zero[string]()) // Output: (blank string)
Zero-Value Comparison Package (zerotern)

The zerotern subpackage provides dedicated utilities for zero-value aware operations:

Function Comparison Type Main Value Fallback Value
VV Direct comparison Direct value Direct value
VF Direct comparison Direct value Function returning value
FV Function comparison Function returning value Direct value
FF Function comparison Function returning value Function returning value
Ref Utilities (zerotern)
Function Ref Handling Fallback Value
SetPV Ref to direct value Direct value
SetPF Ref to direct value Function returning value
Example: Ref Operations

Set ref values with zero-value awareness:

package main

import (
	"fmt"
	"github.com/yylego/tern/zerotern"
)

func main() {
	var value int
	zerotern.SetPV(&value, 42)
	fmt.Println(value) // Output: 42

	value = 7
	zerotern.SetPF(&value, func() int { return 99 })
	fmt.Println(value) // Output: 7 (not changed since now non-zero)
}

⬆️ Source: Source

What makes tern unique?

  1. Enhanced Code clearness: Simplifies condition-based logic with concise expressions
  2. Performance Optimization: Deferred evaluation avoids needless computations
  3. Type Protection: Leverages Go's generics for maximum adaptiveness and robustness
  4. Comprehensive Coverage: Supports various condition-based scenarios including zero-value handling
  5. Simple Integration: Drop-in replacement for complex if-else chains

📄 License

MIT License - see LICENSE.


💬 Contact & Feedback

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Mistake reports? Open an issue on GitHub with reproduction steps
  • 💡 Fresh ideas? Create an issue to discuss
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

Documentation

Overview

Package tern: Flexible tern operation engine to support Go with condition-based evaluation Provides comprehensive tern operations with bool/function conditions and value/function arguments Features both tern operations (condition ? a : b) and two-value operations (condition ? a : zero) Supports deferred evaluation through function parameters to avoid unneeded computation

tern: Go 的灵活三元运算引擎,支持条件评估 提供全面的三元运算,支持布尔/函数条件和值/函数参数 包含三元运算(条件 ? a : b)和二元运算(条件 ? a : 零值) 通过函数参数支持惰性求值,避免不必要的计算

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BF

func BF[T any](condition bool, a func() T) T

BF returns a() if condition is true, otherwise returns zero value BF 如果 condition 为 true 则返回 a(),否则返回零值

func BFF

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

BFF returns a() if condition is true, otherwise returns b() BFF 如果 condition 为 true 则返回 a(),否则返回 b()

func BFV

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

BFV returns a() if condition is true, otherwise returns b BFV 如果 condition 为 true 则返回 a(),否则返回 b

func BV

func BV[T any](condition bool, a T) T

BV returns a if condition is true, otherwise returns zero value BV 如果 condition 为 true 则返回 a,否则返回零值

func BVF

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

BVF returns a if condition is true, otherwise calls and returns b() BVF 如果 condition 为 true 则返回 a,否则调用并返回 b()

func BVV

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

BVV returns a if condition is true, otherwise returns b BVV 如果 condition 为 true 则返回 a,否则返回 b

func FF

func FF[T any](condition func() bool, a func() T) T

FF returns a() if condition() is true, otherwise returns zero value FF 如果 condition() 为 true 则返回 a(),否则返回零值

func FFF

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

FFF returns a() if condition() is true, otherwise returns b() FFF 如果 condition() 为 true 则返回 a(),否则返回 b()

func FFV

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

FFV returns a() if condition() is true, otherwise returns b FFV 如果 condition() 为 true 则返回 a(),否则返回 b

func FV

func FV[T any](condition func() bool, a T) T

FV returns a if condition() is true, otherwise returns zero value FV 如果 condition() 为 true 则返回 a,否则返回零值

func FVF

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

FVF returns a if condition() is true, otherwise calls and returns b() FVF 如果 condition() 为 true 则返回 a,否则调用并返回 b()

func FVV

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

FVV returns a if condition() is true, otherwise returns b FVV 如果 condition() 为 true 则返回 a,否则返回 b

Types

This section is empty.

Directories

Path Synopsis
internal
demos/demo1x command
demos/demo2x command
demos/demo3x command
demos/demo4x command
Package nulltern: Safe tern operation engine to support reference value handling Provides comprehensive tern operations based on nil reference checks Features each combination of reference/function parameters with efficient nil-safe evaluation Supports both direct reference values and function-based reference generation with deferred evaluation
Package nulltern: Safe tern operation engine to support reference value handling Provides comprehensive tern operations based on nil reference checks Features each combination of reference/function parameters with efficient nil-safe evaluation Supports both direct reference values and function-based reference generation with deferred evaluation
Package sametern: Match-based tern operation engine with flexible value matching Provides comprehensive tern operations based on matching comparisons Features each combination of value/function parameters to support first argument, match condition, and result Supports both constant and dynamic matching with efficient evaluation patterns
Package sametern: Match-based tern operation engine with flexible value matching Provides comprehensive tern operations based on matching comparisons Features each combination of value/function parameters to support first argument, match condition, and result Supports both constant and dynamic matching with efficient evaluation patterns
Package slicetern provides safe accessors for slice elements.
Package slicetern provides safe accessors for slice elements.
Package zerotern: Zero-value aware tern operation engine with type-safe evaluation Provides comprehensive tern operations based on zero-value comparisons to support comparable types Features each combination of value/function parameters with efficient zero-value detection Supports both direct value comparison and function-based value generation with deferred evaluation
Package zerotern: Zero-value aware tern operation engine with type-safe evaluation Provides comprehensive tern operations based on zero-value comparisons to support comparable types Features each combination of value/function parameters with efficient zero-value detection Supports both direct value comparison and function-based value generation with deferred evaluation

Jump to

Keyboard shortcuts

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