FileWriter : AutoCloseable & FunctionalInterface


>>Testament.java

import java.io.FileWriter;
import java.io.IOException;

@FunctionalInterface
interface xInstance<L, R extends Throwable>{
  public abstract void accept(L obj) throws R;
}

public class Testament implements AutoCloseable{
  private FileWriter writer;
  private Testament(final String fileName) throws IOException{
    writer = new FileWriter(fileName);
  }
  @Override
  public void close() throws IOException{
    System.out.println("closed...");
    writer.close();
  }
  public void writeToFile(final String mes) throws IOException{
    writer.write(mes);
  }
  public static void exec(final String fileName, final xInstance<Testament, IOException> block) throws IOException{
    try(Testament t = new Testament(fileName)){
      block.accept(t);
    }
  }
  public static void main(String args[]) throws IOException{
    Testament.exec("/Users/someone/Desktop/hoge.txt", w -> w.writeToFile("how are you doing today?\n"));
  }
}

  誤記に因つて五六回程度倒けつつも修正を終える.
f:id:blau_coerulea:20170419201815p:plain
  実行結果
f:id:blau_coerulea:20170419201803p:plain
  fmfm, smartなのかしらそうかしら. 隠蔽されるので簡潔とは成りますが, 慣れないと"......え?"つてなりそう.

  tryを書き忘れてもコンパイルが通ります故, もしそうしてしまつた刻はファイルが自動で閉じられるのを期待するのは潔く諦めませう.

  不用意にリソースを掴んだままにするのを避ける為に, というのが主たる使用目的となります.

Remove all ads

"Hello World" of Rust

  ewe......たつた三十行足らずのsample code[introduction]に転がされる事三十分と少々. これで色々と実際に書いて試せる所へ. 後出し法に乗せられてstack overflowを回つてしまう辺り, 気が早過ぎるかも.
  結論は, きちんと説明文を読み進めてから取りかかれ, と謂う事で.

main.rs

extern crate rand;

use std::io;
use rand::Rng;
use std::cmp::Ordering;

fn main(){
  guess();
}

fn guess(){
  println!("please input your number\n");
  let mut g = String::new();
  io::stdin()
    .read_line(&mut g)
    .ok()
    .expect("failed");
  let secret_number: i32 = rand::thread_rng()
    .gen_range(1, 101);
  let n:i32 = g.trim()
    .parse()
    .expect("wanted a num");
  match n.cmp(&secret_number) {
    Ordering::Less    => println!("bigger than your number"),
    Ordering::Equal   => println!("equal"),
    Ordering::Greater => println!("smaller than your number")
  };
  println!("correct number is {}", secret_number);
}



Cargo.toml

[package]
name = "hello"
version = "0.1.0"
authors = [“author_name”]

[dependencies]
rand="=0.3.15"

f:id:blau_coerulea:20170415123522p:plain

Remove all ads

  That was epic <3
  ten, how to control dandelion my garden?

Remove all ads