What are the differences between Array and Slice in Carbon? I find a document from the official repo. However, it is uncompleted currently.
The following are example codes from the Carbon official repo.
// Carbon:
package Geometry api;
import Math;
class Circle {
var r: f32;
}
fn PrintTotalArea(circles: Slice(Circle)) {
var area: f32 = 0;
for (c: Circle in circles) {
area += Math.Pi * c.r * c.r;
}
Print("Total area: {0}", area);
}
fn Main() -> i32 {
// A dynamically sized array, like `std::vector`.
var circles: Array(Circle) = ({.r = 1.0}, {.r = 2.0});
// Implicitly constructs `Slice` from `Array`.
PrintTotalArea(circles);
return 0;
}
I guess that the Slice is something like std::span, since the C++ version of the codes above uses std::span when the Carbon version uses Slice. Am I correct?
// C++:
#include <math.h>
#include <iostream>
#include <span>
#include <vector>
struct Circle {
float r;
};
void PrintTotalArea(std::span<Circle> circles) {
float area = 0;
for (const Circle& c : circles) {
area += M_PI * c.r * c.r;
}
std::cout << "Total area: " << area << "\n";
}
auto main(int argc, char** argv) -> int {
std::vector<Circle> circles = {{1.0}, {2.0}};
// Implicitly constructors `span` from `vector`.
PrintTotalArea(circles);
return 0;
}
Currently, a first version Arrays exist, while continuing to being worked on, and the Slice type is basically not defined, so it is a bit early to give you a real answer.
As you guessed, it seems like slices might eventually have similarities with std::span, based on some design discussions, but nothing has been approved yet.
You can check the open design proposals on GitHub directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With