Go slices and C slices differ in one fundamental aspect—the Go version embeds both length and capacity, while in C, all we have is a pointer to the first element. This means that in C, length and capacity must be stored somewhere else, such as in another variable.
Let's take the following Go function, which calculates the mean of a series of float64 numbers:
func mean(l []float64) (m float64) {
for _, a := range l {
m += a
}
return m / float64(len(l))
}
If we want to have a similar function in C, we need to pass a pointer together with its length. This will avoid errors such as segmentation fault, which happens when an application tries to gain access to memory that has not been assigned to it. If the memory is still assigned to the application, the result is that it provides access to a memory area with an unknown value, causing...