代码之家  ›  专栏  ›  技术社区  ›  wyc

声明和使用不带结构的模块

  •  0
  • wyc  · 技术社区  · 3 年前

    我有以下没有结构的模块:

    img_util.rs:

    pub mod img_util {
        use image::{ImageBuffer, Pixel};
        use std::{fs::File, io::BufWriter};
    
        fn get_color_type<P>() -> Result<png::ColorType, std::io::Error>
        where
            P: Pixel<Subpixel = u8>,
        {
            match <P as Pixel>::CHANNEL_COUNT {
                4 => Ok(png::ColorType::Rgba),
                3 => Ok(png::ColorType::Rgb),
                _ => Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "Incorrect color channel count / format.",
                )),
            }
        }
    
        fn get_dpi_header_data(dpi: u32) -> Vec<u8> {
            let dpm = 39.370079 * dpi as f32;
            let rounded_dpm = dpm.round() as u32;
    
            let mut data: Vec<u8> = Vec::new();
            data.extend_from_slice(&rounded_dpm.to_be_bytes()); // Pixels per unit in X-direction.
            data.extend_from_slice(&rounded_dpm.to_be_bytes()); // Pixels per unit in Y-direction.
    
            data.push(1); // Indicate that meters are used as unit.
            data
        }
    
        pub fn save_png_with_dpi<P>(
            input_img: &ImageBuffer<P, Vec<u8>>,
            output_img: File,
            dpi: u32,
        ) -> Result<(), std::io::Error>
        where
            P: Pixel<Subpixel = u8>,
        {
            let w = &mut BufWriter::new(output_img);
            let (width, height) = input_img.dimensions();
            let mut encoder = png::Encoder::new(w, width, height);
    
            encoder.set_color(get_color_type::<P>()?);
            encoder.set_depth(png::BitDepth::Eight);
            encoder.set_compression(png::Compression::Best);
    
            let data = get_dpi_header_data(dpi);
            let mut writer = encoder.write_header()?;
    
            writer.write_chunk(png::chunk::pHYs, data.as_slice())?;
            writer.write_image_data(input_img)?;
            Ok(())
        }
    }
    

    lib.rs:

    pub mod img_util;
    

    main.rs:

    use visual_center::img_util::img_util;
    
    img_util::save_png_with_dpi(
        // arguments
    ).unwrap();
    

    我可以使用该模块,但我对必须声明pub-mod-img_util两次(一次在 img_util.rs 另一个在 lib.rs )。或者这可能是声明和使用没有结构的模块的唯一方法?

    1 回复  |  直到 3 年前
        1
  •  2
  •   prog-fh    3 年前

    既然你已经 pub mod img_util; 在里面 lib.rs ,编译器将考虑 img_util.rs 作为板条箱的一个模块。 中的所有内容 img_util.rs 已经在中 img_util 单元 如果您声明 pub mod img_util { ... } 在这个模块中,这意味着您提供(内联的,而不是在另一个文件中) sub 与其父模块名称完全相同的模块(这是巧合,您可以用不同的名称命名它)。

    你只需要删除它 pub mod img_util{…} 。 然后您将在中使用它 main.rs 像

    use visual_center::img_util; // one less
    
    img_util::save_png_with_dpi(
        // arguments
    ).unwrap();
    
    推荐文章