M
Modular10mo ago
jmky

Conditional typing of fields.

Suppose I have the following struct: (in pseudo Mojo)
struct IntWrapper[N: Int]:
@parameter
if N <= 255:
var inner: UInt8
else:
var inner: Int
struct IntWrapper[N: Int]:
@parameter
if N <= 255:
var inner: UInt8
else:
var inner: Int
For usecases where I know that it is definite that the field inner cannot hold values larger than N, then is it possible to type the fields conditionally? You can do this easily in C++, impossible to do in Rust. What about Mojo?
1 Reply
benny
benny10mo ago
I don’t think this is currently supported by a do really like the idea, the closest is can think of is something like this
trait IntWrapper:


struct UIntWrapper[N: Int](IntWrapper):
var inner UInt8

struct SIntWrapper[N: Int](IntWrapper):
var inner: Int

fn createWrapper[N: Int]() -> IntWrapper:
@parameter
if N > 255:
return SIntWrapper[N]()
return UIntWrapper[N]()
trait IntWrapper:


struct UIntWrapper[N: Int](IntWrapper):
var inner UInt8

struct SIntWrapper[N: Int](IntWrapper):
var inner: Int

fn createWrapper[N: Int]() -> IntWrapper:
@parameter
if N > 255:
return SIntWrapper[N]()
return UIntWrapper[N]()
Alternatively you could have the struct take in a type as a parameter, along with N, and figure that out as a separate function The code will be a little messier but you don’t have to do type gymnastics with traits and can just return the passed in type
struct IntWrapper[N: Int, T: DType]():
var inner: T

fn createWrapper[N: Int]() -> IntWrapper:
@parameter
if N > 255:
return IntWrapper[N, Int]()
return IntWrapper[N, UInt8]()
struct IntWrapper[N: Int, T: DType]():
var inner: T

fn createWrapper[N: Int]() -> IntWrapper:
@parameter
if N > 255:
return IntWrapper[N, Int]()
return IntWrapper[N, UInt8]()
you have to define an init function but those are the two easiest ways I can think of implementing what your asking
Want results from more Discord servers?
Add your server