如何创建一个接受i32s迭代器作为值或引用并将它们相加的函数?

时间:2017-09-18 21:47:06

标签: rust

有没有办法让一个函数接受值或引用的迭代器?如果没有,有没有办法重写一个或两个测试,以便他们可以调用相同的 <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Google Maps API v3 Directions Example</title> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js? key=MYKEYHERE&callback=initMap"></script></head> <?php $start = "Leeds"; $end = "Nottingham"; ?> <body> <div id="map"></div> <div id="right-panel"></div> <script type="text/javascript"> var directionsService = new google.maps.DirectionsService(); var directionsDisplay = new google.maps.DirectionsRenderer(); var map = new google.maps.Map(document.getElementById('map'), { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP }); directionsDisplay.setMap(map); directionsDisplay.setPanel(document.getElementById('right-panel')); var request = { origin: <?php echo $start; ?>, destination: <?php echo $end; ?>, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); </script> </body> </html> 函数?

mean

1 个答案:

答案 0 :(得分:2)

你需要声明你将采用一个通用迭代器,它产生的值可以添加到i32并返回i32

use std::ops::Add;

pub fn mean<I>(x: i32, xs: I) -> f64
where
    I: IntoIterator,
    i32: Add<I::Item, Output = i32>,
{
    let (sum, len) = xs.into_iter().fold((x, 1u32), |acc, x| (acc.0 + x, acc.1 + 1));
    f64::from(sum) / f64::from(len)
}

为了增强乐趣,它需要实现IntoIterator,这意味着可以将呼叫站点更改为

super::mean(46, &array)
super::mean(46, iter)