Read Json in Rust

I am trying to read the contents of a Json file in Rust. This file contains an array of points in the plane, for example [[1, 2], [3.5, 2.7], [0, -2.1]].

My first attempt at implementation is

extern crate serialize;
use serialize::json;
use std::io::File;

fn read_points() -> Vec<[f64, ..2]> {
  let contents = File::open(&Path::new("../points.json")).read_to_string().unwrap();
  let points: Vec<Vec<f64>> = json::decode(contents.as_slice()).unwrap();

  points.iter().map(|&v| [v[0], v[1]]).collect::<Vec<[f64, ..2]>>()
}

Now I have two problems with this.

Firstly, I get a compilation error

error: cannot move out of dereference of `&`-pointer

which, apparently, means that my card operation is unsafe. As a full-blown newcomer to Rust, it’s not obvious to me where I am &vin memory. Ideally, I would like to access a base array that supports Vec<f64>, or even better, avoid highlighting the internal vectors that read json directly Vec<[f64, ..2]>.

- - unwrap. , , json . Result, flatmap Scala bind Haskell? , - ?

+4
1

, , and_then() Result, , , : read_to_string() Result<String, IoError>, json::decode() Result<T, DecoderError>, - Rust, .

, RFC, , .

.

, iter() . , - , Iterator<&Vec<f64>>. , , .

&v , v , :

|&v| [v[0], v[1]]  // v is Vec<f64>

:

|r| {              // r is &Vec<f64>
    let v = *r;    // v is Vec<f64>
    [v[0], v[1]]
}

, , int, enums/tuples/etc, Vec<T> , , .

-, & &v ( collect(), ):

points.iter().map(|v| [v[0], v[1]]).collect()

, , - , trait, .

, into_iter() iter():

points.into_iter().map(|v| [v[0], v[1]]).collect()

into_iter() on Vec<T> , T, &T iter(), v Vec<f64>. into_iter() , points , , , points .

. JSON , [f64, ..2], , Rust . Decodable :

extern crate serialize;

use serialize::{Decoder, Decodable};
use serialize::json;

#[deriving(Show)]
struct Point(f64, f64);

impl Decodable for Point {
    fn decode<D: Decoder>(d: &mut D) -> Result<Point, D::Error> {
        d.read_tuple(2, |d| {
            d.read_tuple_arg(0, |d| d.read_f64()).and_then(|e1|
                d.read_tuple_arg(1, |d| d.read_f64()).map(|e2|
                    Point(e1, e2)
                )
            )
        })
    }
}

fn main() {
    let s = "[[1, 2], [3.5, 2.7], [0, -2.1]]";
    let v: Vec<Point> = json::decode(s).unwrap();
    println!("{}", v);
}

( )

, [f64, ..2], Point struct, .

, Decodable Decoder , rustc --pretty=expanded .

, Rust

+12

All Articles