In-place replacement of struct fields

Hey all, I was wondering if someone has a away of changing the underlying data of a tensor in a struct at run time.
struct IOStream
var source: Tensor
fn __init__(inout self):
self.source = Tensor[DType.int8](100)

fn _resize(inout self):
self.source = Tensor[DType.int8](50) # fails as self.source is static
struct IOStream
var source: Tensor
fn __init__(inout self):
self.source = Tensor[DType.int8](100)

fn _resize(inout self):
self.source = Tensor[DType.int8](50) # fails as self.source is static
Can you instead change the pointer of the underlying data of self.sourceto another pointer, doing in place change of the tensor? similar to rust's mem::replace Edit1: Intrestingly the error does not appear with mojo run but when the binary is build with mojo build and then ./path/to/binary
2 Replies
Michael K
Michael K9mo ago
I am not sure what is a real coding problem and what is just a formatting problem for what is on discord. But this code runs without error:
struct IOStream:
var source: Tensor[DType.int8]

fn __init__(inout self):
self.source = Tensor[DType.int8](100)

fn _resize(inout self):
self.source = Tensor[DType.int8](50) # fails as self.source is static


fn main():
var stream = IOStream()
stream._resize()
struct IOStream:
var source: Tensor[DType.int8]

fn __init__(inout self):
self.source = Tensor[DType.int8](100)

fn _resize(inout self):
self.source = Tensor[DType.int8](50) # fails as self.source is static


fn main():
var stream = IOStream()
stream._resize()
Since it is just creating a new tensor the size of the tensor being replaced is irrelevant. I am not sure what is meant by self.source being static. If you are trying to do something fancier like update the size I am not sure there is much of a distinciton between creating a new tensor or replacing the pointer in the old tensor. Both will require a new poiinter and possibly a copy which will be the slow parts. So probably creating a new tensor is easiest so all the size information gets created correclty.
Mohamed Mabrouk
Mohamed MabroukOP9mo ago
In my case it runs without error in debug mode (using run), it failes if you tried to build a binary first and ran it, I will edit the post It works now, I think I had another bug in the code, Thnx
Want results from more Discord servers?
Add your server