将基本类型转换为T(也是原始类型)是Rust

时间:2017-01-06 13:32:21

标签: rust

因为我在将原始类型(usize)转换为T时遇到问题。

现在我有这样的事情:

fn calculate_center_of_points(points: &Vec<point::Point<T>>) -> Option<point::Point<T>>
{
    if points.len() == 0
    {
        return None
    }
    let tmp: T = Default::default();
    let mut pointCount : T = Default::default();
    let mut center_point = point::Point::new(tmp, tmp);
    for p in points
    {
        center_point.move_point(p.x,p.y);
        pointCount = pointCount + T::one();
    }
    let center_point = point::Point::new(center_point.x / pointCount, center_point.y / pointCount);
    Some(center_point)
}

但是我希望得到像

这样的东西
for p in points
    {
        center_point.move_point(p.x,p.y);
        pointCount = pointCount + T::one();
    }
    let center_point = point::Point::new(center_point.x / points.len() as T, center_point.y / points.len() as T);

我已经抬起了这个号码,但是我找不到我希望在我的&#34;好的&#34;溶液

1 个答案:

答案 0 :(得分:2)

use num::FromPrimitive; fn get_len<T:FromPrimitive>(v: Vec<T>) -> Option<T> { T::from_usize(v.len()) } crate有一个FromPrimitive特征,看起来像你想要的。

所以你要像使用它一样:

T

任何FromPrimitive显然都需要实施BigInt;根据文档,它附带了原始数字类型和BigUint / <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <proxies> <proxy> <id>optional</id> <active>true</active> <protocol>http</protocol> <host>myproxyserver.name.org</host> <port>8080</port> <nonProxyHosts>localhost|myserver</nonProxyHosts> </proxy> </proxies> <servers> <server> <id>my.snapshots</id> </server> </servers> <mirrors> <mirror> <id>Central</id> <url>http://repo.maven.apache.org/maven2</url> <mirrorOf>my.snapshots</mirrorOf> </mirror> <mirror> <id>archiva.default</id> <mirrorOf>Central</mirrorOf> <url>http://myserver:8080/repository/internal/</url> </mirror> <mirror> <id>my.snapshots</id> <mirrorOf>Central</mirrorOf> <url>http://myserver:8080/repository/snapshots</url> </mirror> </mirrors> <profiles> <profile> <id>internal</id> <activation> <activeByDefault>true</activeByDefault> </activation> <repositories> <repository> <id>archiva.internal</id> <name>Archiva Managed Internal Repository</name> <url>http://myserver:8080/repository/internal/</url> <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases> <snapshots><enabled>false</enabled></snapshots> </repository> <repository> <id>archiva.snapshots</id> <name>Archiva Managed Internal Repository</name> <url>http://myserver:8080/repository/snapshots/</url> <releases><enabled>false</enabled></releases> <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots> </repository> </repositories> </profile> </profiles> <activeProfiles> <activeProfile>internal</activeProfile> </activeProfiles> 的实现。