Hello!
I have a struct S
that contains a Union{Some{String}, Nothing}
and I’m accessing the value at a time when it’s guaranteed to be a Some{String}
(unless someone accesses the private fields of the struct). Can I access the wrapped String value without Julia emitting code for a type assertion?
Concrete example that already includes an assert:
struct S1
v::Union{Some{String}, Nothing}
S1() = new(Some("foo"))
end
function f1(s::S1)
# By the time this function executes, v is guaranteed to contain a value
# of type `Some{String}`.
@assert typeof(s.v) == Some{String}
return something(s.v)
end
# The challenge is to make Julia emit some code that doesn't contain any
# error handling for the case where v is `nothing`.
@code_llvm f1(S1())
Harder mode that’s closer to my real problem:
struct S2
v::Vector{Union{Some{String}, Nothing}}
S2() = new([Some("foo")])
end
function f2(s::S2)
# By the time this function executes, v[1] is guaranteed to contain a value
# of type `Some{String}`.
v1 = @inbounds s.v[1]
@assert typeof(v1) == Some{String}
return something(v1)
end
# The challenge is to make Julia emit some code that doesn't contain any
# error handling for the cases where v[1] is `nothing` or out of bounds.
@code_llvm f2(S2())
I’m mostly asking out of curiosity, but if it is possible to omit these checks then I might be able to speed up a data structure I’ve written (though I won’t know until I do it whether the speed up will be worth the extra risk).
Thanks!