2

当我尝试将 nom's 转换CompleteStr为 a Stringin 时named!,我收到一条错误消息,指出它正在返回 a Result

named!(letter_cs<CompleteStr,String>,
    map_res!(
        alpha,
        |CompleteStr(s)| String::from(s)
       )
); 

会抛出错误

error[E0308]: mismatched types                                                                                                                          
  --> src/year2015/day_7.rs:16:1                                                                                                                        
   |                                                                                                                                                    
16 | / named!(letter_cs<CompleteStr,String>,                                                                                                            
17 | |     map_res!(                                                                                                                                    
18 | |         alpha,                                                                                                                                   
19 | |         |CompleteStr(s)| String::from(s)                                                                                                         
20 | |          )                                                                                                                                       
21 | | );                                                                                                                                               
   | |__^ expected struct `std::string::String`, found enum `std::result::Result`                                                                       
   |                                                                                                                                                    
   = note: expected type `std::string::String`                                                                                                          
              found type `std::result::Result<_, _>`                                                                                                    
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) 
4

1 回答 1

3

map_res!期望一个返回 aResult作为第二个参数的函数,这就是为什么这样map_res!命名的原因。您还可以在 nom 的文档中的“类型”中看到它:

map_res!(I -> IResult<I,O>, O -> Result<P>) => I -> IResult<I, P>

但是,String::from不返回结果;String::from(s)错误的类型也是如此map_res!。相反,您应该使用map!具有这种“类型”的常规map!(I -> IResult<I,O>, O -> P) => I -> IResult<I, P>

#[macro_use]
extern crate nom;

use nom::types::CompleteStr;
use nom::alpha;

named!(letter_cs<CompleteStr,String>,
    map!(
        alpha,
        |CompleteStr(s)| String::from(s)
       )
);
于 2018-11-27T08:17:19.650 回答