Skip to content

Instantly share code, notes, and snippets.

@guidorice
Last active December 9, 2023 16:47
Show Gist options
  • Save guidorice/799a2eb189afffdd3e15493c71065480 to your computer and use it in GitHub Desktop.
Save guidorice/799a2eb189afffdd3e15493c71065480 to your computer and use it in GitHub Desktop.
parameter deduction in mojo (0.6) without traits
@value
struct Wrappee[dtype: DType = DType.float16]:
"""
Stores an int as a SIMD value.
Defaults to float16.
"""
var value: SIMD[dtype]
fn __init__(inout self, x: Int):
self.value = x
fn __copyinit__(inout self, existing: Self):
self.value = existing.value
struct Wrapper[dtype: DType]:
"""
A struct composed of a Wrappee.
"""
var value: Wrappee[dtype]
fn __init__(inout self, w: Wrappee[dtype]):
self.value = w
fn main():
# using lower-level API, we definitely want to optionally specify a dtype
let pi = Wrappee(3.14)
let more_pi = Wrappee[DType.float64](3.14)
# using higher level API, want to optionally specify a dtype, but user usually will not want to deal with it.
let try_wrapper = Wrapper(pi)
print(try_wrapper.dtype, try_wrapper.value.value)
let try_wrapper_more = Wrapper(more_pi)
print(try_wrapper_more.dtype, try_wrapper_more.value.value)
@guidorice
Copy link
Author

float16 [3.140625, 3.140625, 3.140625, 3.140625, 3.140625, 3.140625, 3.140625, 3.140625]
float64 [3.1400000000000001, 3.1400000000000001]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment