在结构中存储不可变路径的正确方法是什么?

时间:2015-09-23 03:58:42

标签: path rust ownership

以下代码有效,但不确定它是否正确。几个问题:

  • 我应该使用Path还是PathBuf
  • 我应该使用AsRef吗?
  • 我是否需要PathBuf::from(path)才能拥有结构所拥有的路径?
use std::fmt;
use std::path::PathBuf;

struct Example {
    path: PathBuf,
}

impl fmt::Display for Example {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.path.to_str().unwrap())
    }
}

impl Example {

    fn new(path: &PathBuf) -> Example {
        // Do something here with path.
        Example {
            path: PathBuf::from(path),
        }
    }
}

fn main() {
    let x = Example::new(&PathBuf::from("test.png"));
    println!("{}", x);
}

某些上下文:我试图对应该知道自己路径的文件进行高级抽象。也许设计是完全错误的。

1 个答案:

答案 0 :(得分:11)

此问题与var ctx = canvas.getContext('2d'), img = new Image; img.onload = draw; img.crossOrigin = 'anonymous'; img.src = "drawing/templates/drawing-pic4.png"; var outline, origOutline, outlineCtx; function draw(color) { ctx.clearRect(0,0,canvas.width,canvas.height); // onload if(typeof color !== 'string') color = 'white'; var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array s = 5, // scale i = 0, // iterator x = 5, // final position y = 5; // draw images at offsets from the array scaled by s for(; i < dArr.length; i += 2) ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s); // fill with color ctx.globalCompositeOperation = "source-in"; ctx.fillStyle = color; ctx.fillRect(0,0,canvas.width, canvas.height); // keep only the outline ctx.globalCompositeOperation = "destination-out"; ctx.drawImage(img, x, y); origOutline = ctx.getImageData(0,0,canvas.width, canvas.height).data; // store the imageData in a new Canvas outline = canvas.cloneNode(true); outlineCtx = outline.getContext('2d') outlineCtx.drawImage(canvas,0,0); // draw image in original mode ctx.globalCompositeOperation = "source-over"; ctx.drawImage(img, x, y); } var w= 10; canvas.onclick = function(e){ var rect = canvas.getBoundingClientRect(); var x = e.clientX-rect.left, y = e.clientY-rect.top; var pixels = ((y*canvas.width)+x)*4; showLog("pixels: "+pixels); if(origOutline[pixels+3]!==0) { showLog("in out line: "+origOutline[pixels+3]); } // not transparent ? if(outlineCtx.getImageData(x,y,1,1).data[3]!==0){ ctx.strokeStyle = "#0000ff"; ctx.lineWidth = w; ctx.lineJoin = ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x,y); ctx.stroke(); ctx.closePath(); } else{ showLog("else"); } } vs String几乎相同,如果有帮助的话。 &strPathBufString&Path。所以:

如果您希望结构拥有它,请存储&str。如果你不知道自己想要什么,请从这里开始。

如果您只想引用路径,请存储PathBuf。根据您正在做的事情,这可能是您想要的,但如果您不知道,那可能不正确。