-
Notifications
You must be signed in to change notification settings - Fork 49
Lists and Arrays
A list in regular Python can hold a variable number of items of any type, they do not all have to be of the same type. How lists and arrays work in Rusthon depends on the target backend. JavaScript lists (called Arrays) support the regular Python rules for a list, so when using the JavaScript backend, there is not much you have to think about.
a = [1, None, "hello"]
The above list syntax is compatible with the JavaScript backend.
For the other backends: Go, Rust and C++, a list is translated to the native vector type, and needs to be typed, the syntax is inspired by Go.
a = []int( 1,2,3 )
As a special case, a list than contains a literal int, float, or string, will have its type inferred automatically. Below produces the same results as above.
a = [1,2,3]
In both cases above the list will become std::shared_ptr<std::vector<int>>
with the C++ backend.
Fixed sized arrays can be created with this syntax:
a = [4]int(1,2,3,4)
Above creates a fixed size array of length 4, this becomes std::shared_ptr<std::array<int>>
with the C++ backend.
Array comprehension syntax:
a = []int( x for x in range(10) )
You do not have to think much about pointers in Rusthon when using the Rust or C++ backends. When a new vector or array is created, it is always wrapped by shared reference counting pointer, in C++ that's std::shared_ptr<T>
and in Rust it is Rc<RefCell<T>>
.
The syntax to type a function argument as a type of vector is:
def myfunc( a: []int ):
a.append( 100 )
Above a
is typed as a vector of integers. If you are coming from Go or C++ this may look incorrect, because it looks like the function takes a copy of the array, and so appending to it the result would not appear in the caller - this is not pythonic. In Rusthon, just like Python, a vector is always passed by reference (not a copy) from the caller to the called function. The shared pointer is implicit, in the C++ backend a:[]int
becomes std::shared_ptr<std::vector<int>> a
.
a = [][]int()
The .append
method is translated into the proper method call for the native vector type. In C++ it becomes .push_back
.
TODO
*fix hack in rust and c++ backend where .append
is a special case.