Skip to content

Instantly share code, notes, and snippets.

View hussachai's full-sized avatar

Hussachai Puripunpinyo hussachai

View GitHub Profile
@hussachai
hussachai / actix-web-handler-.rs
Created April 2, 2022 05:52
Error Handling in Rust that Every Beginner should Know (actix-web-handler)
// main.rs
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(move || {
App::new()
.service(web::resource("/queue/{id}").route(web::get().to(queue_handler::handle)))
}).bind("0.0.0.0:8080")?.run().await
}
// queue_handler.rs
@hussachai
hussachai / recovering_from_panic.rs
Created April 1, 2022 21:39
Error Handling in Rust that Every Beginner should Know (recovering from a panic)
fn parse_to_f64(s: &str) -> f64 {
s.parse::<f64>().unwrap()
}
let result = std::panic::catch_unwind(|| {
println!("{}", parse_to_f64("12.34"));
});
assert!(result.is_ok());
let result = std::panic::catch_unwind(|| {
println!("{}", parse_to_f64("abcdef"));
@hussachai
hussachai / cicle_equation.rs
Created April 1, 2022 06:20
Error Handling in Rust that Every Beginner should Know (Rust Way)
fn square(s: &str) -> Result<f64, ParseFloatError> {
s.parse::<f64>().map (|i| i * i)
}
fn calculate(x: &str, y: &str) -> Result<f64, ParseFloatError> {
let x2 = square(x)?;
let y2 = square(y)?;
Ok((x2 + y2).sqrt())
}
@hussachai
hussachai / circle_equation.scala
Last active April 1, 2022 06:02
Error Handling in Rust that Every Beginner should Know (Scala way)
def square(s: String): Try[Double] = Try {
val i = s.toDouble
i * i
}
def calculate(x: String, y: String): Try[Double] = {
for {
x <- square(x)
y <- square(y)
} yield Math.sqrt(x + y)
@hussachai
hussachai / circle_equation.go
Created April 1, 2022 05:48
Error Handling in Rust that Every Beginner should Know (Go way)
func square(s string) (float64, error) {
i, e := strconv.ParseFloat(s, 64)
return i * i, e
}
func calculate(x string, y string) (*float64, error) {
x2, e := square(x)
if e != nil {
return nil, e
}
y2, e := square(y)
@hussachai
hussachai / result_unwrap.rs
Created April 1, 2022 04:53
Error Handling in Rust that Every Beginner should Know Snippet 2
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
}
@hussachai
hussachai / option_unwrap.rs
Created April 1, 2022 04:51
Error Handling in Rust that Every Beginner should Know Snippet 1
pub const fn unwrap(self) -> T {
match self {
Some(val) => val,
None => panic!("called `Option::unwrap()` on a `None` value"),
}
}
pub fn expect(self, msg: &str) -> T {
match self {
Some(val) => val,
None => expect_failed(msg),
data class Currency(val value: BigDecimal, val code: String) {
constructor(v: Int, code: String): this(BigDecimal(v), code)
fun convert(toCode: String): Currency {
return Currency(convert(this, toCode), toCode)
}
private fun convert(fromCurrency: Currency, toCode: String): BigDecimal {
//1 USD = 1.27082 CAD
return if (fromCurrency.code == "USD" && toCode == "CAD") {
fromCurrency.value * BigDecimal(1.27)
} else if (fromCurrency.code == "CAD" && toCode == "USD") {
@hussachai
hussachai / BadBidiFlow.scala
Last active June 13, 2017 23:45
Bad snippet! Don't do it.
object BadBidiFlow extends App {
implicit val system = ActorSystem()
implicit val ec = system.dispatcher
implicit val materializer = ActorMaterializer()
val source = Source.fromIterator(() => Seq("1", "2a", "3").toIterator)
val sink = Sink.foreach(println)
val endFlow = Flow.fromFunction[String, (String, Try[Int])]{ a => (a, Try(a.toInt)) }
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
import org.scalameter.{Key, Warmer, _}
import scala.annotation.tailrec
import scala.util.{Failure, Success, Try}
/**