3 ms·
Take Go's slices, for example Realize a Go []int ("slice of int") is just a C struct like this, passed by value: struct intSlice { int* addr; in
by 37ef_ced3 6y ago
Take Go's slices, for example
Realize a Go []int ("slice of int") is just a C struct like this, passed by value:
struct intSlice {
int* addr;
int len;
int cap;
};
The memory at addr is not owned by the slice. All the slice operations are simply notation for manipulating the struct. Go's garbage collection makes the whole thing work well
This can be confusing if you're used to C++'s std::vector (which owns the memory) or Python's slices. Go's slices are a shallow pointer/length system exactly like is used in C all the time. For example:
void sort(int* addr, int len);
becomes
func sort(a []int)
A Go slice is just a formalization of C's pointer/length idiom, with terse notation for manipulation
- traes 6y agoI'm not really sure saying that features in Go can be modeled in C really suggests that they are similar as languages. Syntax is very important.
- nyanpasu64 6y agoGo's slices don't act like what I thought were called "non-owning references"(Rust's &/&mut [T] or C++'s std::span<T/T const>), which reference memory whose lifetime is bounded by something else (like a vector or array or shared pointer). Instead it's "shared ownership" where memory is referenced by one or more slices (and no single owner) which can reference and mutate the slice simultaneously, and it's freed by the GC sometime after all the slices are gone. This reminds me of Numpy's ndarrays, which act more like "owning containers" (which may sometimes share ownership and alias) than "non-owning references".
- erik_seaberg 6y agoSlices are kind of a mess. They should either be uniqueness types or passed by reference (the way maps and channels are, and NIO buffers from Java). Instead they’re passed by value so multiple copies exist whose sizes and sometimes contents aren’t in sync.
- mhh__ 6y agoSlices should be the absolute bare minimum for a modern systems language, it's not really a reason to switch in my case If I want to write flat/simple code I'll just C, Go doesn't really offer anything to me because I want to be relatively low-level and able to make the compiler save my time.