【发布时间】:2019-12-20 23:14:05
【问题描述】:
我正在尝试在 FreeBSD 12 下测试 Rust 1.39 中的一些语言特性,并与 Free Pascal 3.0.4 进行比较,以获得一个简单的通用点集合,其中包含由字符串键寻址的 2D 点。不幸的是,泛型类型声明的代码不会在很早的状态下编译并停止:
error[E0106]: missing lifetime specifier
--> src/main.rs:11:31
|
11 | type TPointMap = BTreeMap<&TString, TPoint>;
|
如何重写 Rust 代码?
详情:
为了测试语言行为,我用 Rust 和 Pascal 编写了两个小程序,“在语法上”处理相同的上下文。 Pascal 程序是一个简单的声明:
- 一些普通类型,一个记录类型和一个通用地图容器,
- 之后将使用它来定义一个点,将该点存储在一个新分配的地图中,
- 通过key搜索点并将数据写入
STDIO - 最后释放地图。
program test;
uses fgl; { Use the free pascal generics library }
type
TDouble = Double; { Define a 64 bit float }
TString = String; { Define a string type }
TPoint = record { Define a point record }
X : TDouble; { Coordinate X }
Y : TDouble; { Coordinate Y }
end;
{ Define a map of points with strings as key }
TPointMap = specialize TFPGMap<TString, TPoint>;
{ Test program }
var
map : TPointMap; { Declare the map variable }
point : TPoint; { Declare a point variable }
found : TPoint; { Varaiable for a found point }
key : TString; { Variable to address the point in the map }
begin
map := TPointMap.create; { Allocate a new ma container }
with point do begin { Set the point variable }
x := 1.0; y := 2.0;
end;
key := '123'; { Set the key address to '123' }
map.add(key,point); { Store the point in the map }
{ Search the point an write the result in the rusty way }
case map.TryGetData(key, found) of
true : writeln('X: ',found.X:2;, ' Y:', found.Y:2:2);
false : writeln('Key ''',key,''' not found');
end;
map.free; { De-allocate the map }
{ Plain types are de-allocated by scope }
end.
程序编译并给我:
$ ./main
X: 1.00 Y:2.00
这是我错误的 Rust 版本的代码:
use std::collections::BTreeMap; // Use a map from the collection
type TDouble = f64; // Define the 64 bit float type
type TString = str; // Define the string type
struct TPoint { // Define the string type
x: TDouble, // Coordinate X
y: TDouble, // Coordinate Y
}
// Define a map of points with strings as key
type TPointMap = BTreeMap<&TString, TPoint>;
// Test program
fn main() {
let point = TPoint { x: 1.0, y: 2.0 }; // Declare and define the point variable
let mut map = TPointMap::new(); // Declare the map and allocate it
let key: TString = "123"; // Declare and define the address of point
map.insert(&key, point); // Add the point to the map
// search the point and print it
match map.get(&key) {
Some(found) => println!("X: {} Y: {}", found.X, found.y),
None => println!("Key '{}' not found", key),
}
// map is de-allocated by scope
}
备注:由于借用和所有权的概念,我知道某些代码行不能在 Rust 代码中使用。线
match map.get(&key)...
就是其中之一。
【问题讨论】: