Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sandyspiers/typednamedtuples.jl
Make your named-tuples type-safe!
https://github.com/sandyspiers/typednamedtuples.jl
julia
Last synced: about 2 months ago
JSON representation
Make your named-tuples type-safe!
- Host: GitHub
- URL: https://github.com/sandyspiers/typednamedtuples.jl
- Owner: sandyspiers
- License: mit
- Created: 2024-08-06T06:46:36.000Z (5 months ago)
- Default Branch: main
- Last Pushed: 2024-11-18T22:53:28.000Z (about 2 months ago)
- Last Synced: 2024-11-18T23:47:08.850Z (about 2 months ago)
- Topics: julia
- Language: Julia
- Homepage:
- Size: 7.81 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# TypedNamedTuples.jl
[![Build Status](https://github.com/sandyspiers/TypedNamedTuples.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/sandyspiers/TypedNamedTuples.jl/actions/workflows/CI.yml?query=branch%3Amain)
[![Coverage](https://codecov.io/gh/sandyspiers/TypedNamedTuples.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/sandyspiers/TypedNamedTuples.jl)
[![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle)
[![Aqua](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl)This package provides two macros, `@TypedNamedTuple` and `@MutableTypedNamedTuple`.
These macros create struct types that behave like named tuples but have enforced types.
You can use them like regular named tuples (and even mutable ones), with the added benefit of type safety, making them useful for function extension and multiple dispatch.For example:
```julia
julia> using TypedNamedTuplesjulia> @TypedNamedTuple ExampleType;
julia> ex = ExampleType(a=2, b=1:10, c=:hello, d=false)
ExampleType(a = 2, b = 1:10, c = :hello, d = false)julia> ex.a
2julia> typeof(ex)
ExampleTypejulia> keys(ex)
(:a, :b, :c, :d)julia> values(ex)
(2, 1:10, :hello, false)julia> get(ex, :a, nothing)
2julia> f(ex::ExampleType) = ex.a
f (generic function with 1 method)julia> f(ex)
2julia> f(2)
ERROR: MethodError: no method matching f(::Int64)Closest candidates are:
f(::ExampleType)
@ Main REPL[12]:1Stacktrace:
[1] top-level scope
@ REPL[14]:1
```In fact, we can do all the same as a mutable type:
```julia
julia> @MutableTypedNamedTuple MutType
MutTypejulia> m = MutType(x=5)
MutType(x = 5,)julia> m.x
5julia> m.x *= 2
10julia> print(m)
MutType(x = 10,)julia> m.a = :hello
:hellojulia> m
MutType(x = 10, a = :hello)
```As you can see, we can both modify elements _and_ and new ones!
Note that it is very expensive to mutate, so its best to do so sparingly.
If you have to mutate a lot, this is probably not the best tool to use.