Serde custom Deserialize error

  1. Here is my code
use super::*;

use std::fs::File;
use std::io::prelude::*;
use std::fmt;
use serde_json::Value;
use serde::de::{Deserialize, Deserializer, Visitor};
use serde::de::SeqAccess;
use serde::de::MapAccess;

pub struct TokenLoc {
    start: i32,
    end: i32,

pub struct Article {
    charoffset: Vec<Vec<TokenLoc>>,
    text: Vec<Vec<String>>

impl <'de> Deserialize<'de> for Article {
    fn deserialize<D>(deserializer: D) -> Result<Article, D::Error> where
        D: Deserializer<'de> {

        struct ArticleVisitor;

        impl<'de> Visitor<'de> for ArticleVisitor {
            type Value = Article;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct ARticle")

            fn visit_map<A>(self, mut access: A) -> Result<Article, A::Error>
                    A: MapAccess<'de>,
                while let Some(key) = access.next_key()? {
                    println!("{:?}", key);


        deserializer.deserialize_map(ArticleVisitor {})
  1. Here is the error rustc is telling me:
43 |                 while let Some(key) = access.next_key()? {
   |                                ^^^ cannot infer type
  1. What type should I be annotating it with? (I'm expecting it to be a String).

  2. How do I even annotate a "while let Some(key) ..." line?

  3. (Ideal answer would be if you could just rewrite that one line for me.) Thanks!

while let Some(key) = access.next_key::<TheKeyType>()? {


@sfackler : This worked, thanks!

I'm looking at serde-1.0.75/src/de/, and I see:

    fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error>
        K: Deserialize<'de>,

So what's happening here is that the ::<TheKeyType> is being passed as the <K> which then defines the type we want right?

Yes. Search for “turbofish” to get more info.

1 Like