Primrose Docs
  • Home
    • ⛓️Blockchain
      • Avalanche
        • What is AVAX?
      • Ethereum
        • Ethereum Cancun Upgrade Explained(draft)
        • go-ethereum: gas estimate
        • Blockchain Transaction Lifecycle
        • Mempool
        • Gas optimization in Solidity, Ethereum
      • Solidity DeepDive
        • Meta transaction
        • solidity: patterns
        • UUPS vs Transparent
        • Solidity Interface
        • Smart contract storage
        • ERC-2981 Contract
        • Solidity modifier
        • Solidity delete keyword
        • How To Make NFTs with On-Chain Metadata - Hardhat and JavaScript
        • How to Build "Buy Me a Coffee" DeFi dapp
        • How to Develop an NFT Smart Contract (ERC 721) with Alchemy
        • Upgradeable Contract
        • Smart Contract Verification
      • Common
        • Eigenlayer
        • MultiSig(draft)
        • Chain-Based Proof-of- Stake, BFT-Style Proof-of-Stake
        • Byzantine Fault Tolerance
        • Zero-knowledge
        • Hierarchical Deterministic Wallet
        • Maker DAO
        • Defi
        • Uniswap
        • IBC
        • Cosmos
        • Gossip Protocol
        • Tendermint
        • UTXO vs Account
        • Blockchain Layer
        • Consensus Algorithm
        • How does mining work?
        • Immutable Ledger
        • SHA256 Hash
        • Filecoin
        • IPFS - InterPlanetary File System
        • IPFS와 파일코인
        • Livepeer
        • Layer 0
      • Bitcoin
        • BIP for HD Wallet
        • P2WPKH
        • Segwit vs Native Segwit
    • 📖Languages
      • Javascript/Typescript
        • Hoisting
        • This value in Javascript
        • Execution Context
        • About Javscript
        • tsconfig.json
        • Nest js Provider
        • 'return await promise' vs 'return promise'
      • Python
        • Pythonic
        • Python: Iterable, Iterator
        • Uvicorn & Gunicorn
        • WSGI, ASGI
        • Python docstring
        • Decorator in Python
        • Namespace in Python
        • Python Method
      • Go
        • GORM+MySQL Connection Pool
        • Context in golang
        • How to sign Ethereum EIP-1559 transactions using AWS KMS
        • Mongo DB in golang(draft)
        • Golang HTTP Package
        • Panic
        • Golang new/make
        • golang container package
        • errgroup in golang
        • Generic Programming in Golang
        • Goroutine(draft)
    • 📝Database
      • MongoDB in golang
      • Nested loop join, Hash join
      • DB Query plan
      • Index
      • Optimistic Lock Pessimistic Lock
    • 💻Computer Science
      • N+1 query in go
      • Web server 를 구성할 때 Thread, Process 개수를 어떻게 정할 것인가?
      • CAP
      • Socket programming
      • DNS, IP
      • URL, URI
      • TLS과 SSL
      • Caching(draft)
      • Building Microservices: Micro Service 5 Deploy Principle
      • Red Black Tree
      • AOP
      • Distributed Lock
      • VPC
      • Docker
      • All about Session and JWT
      • Closure
      • Singleton Pattern
      • TCP 3 way handshake & 4 way handshake
      • Race Condition
      • Process Address Space 
      • Call by value, Call by reference, Call by assignment
      • Zookeeper, ETCD
      • URL Shortening
      • Raft consensus
      • Sharding, Partitioning
    • 📒ETC
      • K8S SIGTERM
      • SQS
      • Git Branch Strategy: Ship / Show / Ask
      • Kafka
      • Redis Data Types
      • CI/CD
      • How does Google design APIs?
      • Minishell (42 cursus)
      • Coroutine & Subroutine
      • Redis
Powered by GitBook
On this page
  1. Home
  2. Languages
  3. Go

Generic Programming in Golang

Source : [Tucker’s Go Programming]

What is Generic Programming ?

Let’s know about generic programming, and also why we should use it.

Static polymorphism supports the concept of generic programming.

The definition of generalized programming is not generally agreed. (As if there is no definition of object-oriented programs that everyone accepts )

But we can understand generic programming by comparing simple examples.

Let’s see add function below.

func add(a, b int) int {
  return a + b
}

Since Golang is a strong type language, an error will occur if you insert a non-int type parameter as shown in the example below.

func main() {
  result := add(0.25, 0.75)
  fmt.Println(result)
}

As such, making functions separately for each type, such as int8, int16, float64, is a very cumbersome task.

And if the function behavior changes, the maintenance is not good because you have to change all the functions.

Generic programming allows you to address this issue as follows:

func add[T constraints.Integer | contraints.Float](a, b T) T {
  return a + b
}

Generic functions are functions that operate on different types through type parameters, such as the add() function discussed earlier.

// Define Function name(Primrose) and type parameter(T constraint)
func Primrose[T contraint](p T) {
  ...
}

Generic functions are defined as above.

Write down the func function keyword and then the function name.

Then open the brackets and write down the type parameters.

The type parameter is the parameter name, and in the figure above, T is the parameter name.

Then write down the type limit. You can write multiple type parameters as needed.

Then close the brackets, open the brackets, and write inputs and outputs like a normal function.

The type parameter name used for the type parameter can be used instead of a specific type.

Simple example

func Print[T ant](a, b T) {
  fmt.Println(a, b)
}

func main() {
  // OK
  Print(1, 2)
  Print(3.14, 1.43)
  Print("Hello", "World")

  // Error !
  Print(1, "Hello")
}

Solution

func Print[T1 any, T2 any](a T1, b T2) {
  fmt.Println(a, b)
}

func PrintInterface(a, b interface{}) {
  fmt.Println(a, b)
}

func main() {
  // ... Two function will get same result.
}

We can also apply type restriction

func add[T Integer](a, b T) T {
  return a + b 
}

Advanced type restriction

type Integer interface {
  ~ int8 | ~int16 | ~int32 | ~int64 | ~int
}

func add[T Integer](a, b T) T {
  return a + b
}

type MyInt int

func main() {
  // OK! 
  add(1, 2)
  var a MyInt = 3
  var b MyInt = 5
  add(a, b)
}
Previouserrgroup in golangNextGoroutine(draft)

Last updated 1 year ago

📖