[C++] 谷歌发布开源开发语言 Carbon : 号称将替代 C++

项目的 Github 地址为: https://github.com/carbon-language/carbon-lang

在近日举行的 CppNorth 开发者大会上,谷歌工程师 Chandler Carruth 宣布了名为 “Carbon” 的全新开源开发语言,并称它将是 C++ 的继任者。Chandler Carruth 表示,Carbon 拥有与 C++ 的“双向互操作性”,也就是说开发者可以直接在 Carbon 语言的程序中使用 C++,这大大提升了项目迁移的便捷性。

谷歌在开发该语言的时候,就将接替 C++ 作为了核心目标,它拥有大量与 C++ 相契合的特性,一个熟练的 C++ 开发者将能够迅速上手 Carbon ,并熟练进行程序的编辑

C++

// 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;
}

Carbon

// 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;
}

Mixed

// C++ code used in both Carbon and C++:
struct Circle { float r;
}; // Carbon exposing a function for C++:
package Geometry api;
import Cpp library "circle.h";
import Math; fn PrintTotalArea(circles: Slice(Cpp.Circle)) { var area: f32 = 0; for (c: Cpp.Circle in circles) { area += Math.Pi * c.r * c.r; } Print("Total area: {0}", area);
} // C++ calling Carbon:
#include <vector>
#include "circle.h"
#include "geometry.carbon.h" auto main(int argc, char** argv) -> int { std::vector<Circle> circles = {{1.0}, {2.0}}; // Carbon's `Slice` supports implicit construction from `std::vector`, // similar to `std::span`. Geometry::PrintTotalArea(circles); return 0;
}