#how to pass struct as argument

1 messages · Page 1 of 1 (latest)

fair igloo
#
fn mul(self: *Self, comptime k: usize, input: Matrix(T, m, k)) Matrix(T, n, k) {
  input.print() <-- expected type '*math.Matrix(f32,2,4)', found '*const math.Matrix(f32,2,4)'

how do i make the struct argument non-const?

upbeat yew
#

You can pass the structure by reference:

fn mul(self: *Self, comptime k: usize, input: *Matrix(T, m, k)) ...
peak ether
#

Function parameters are immutable because they may be a copy of the caller's value

#

So it is probably a bug to try to mutate it

upbeat yew
#

In Zig, it's idiomatic to pass immutable structs by value, even when you might pass them by const pointer in C (this is optimized out by the compiler, called copy elision). However, if you need to pass them mutably, you have to provide a reference which you dereference and assign to.

peak ether
#

It's just an optimization that Zig can make, but there's no guarentee that it will.

#

As with any optimization, you shouldn't rely on it.

upbeat yew