Compile Rust to WebAssembly on Mac
This content is same as below.
Install necessary modules from Homebrew
- cmake
- emscripten
$brew install cmake emscripten
After installing emscripten
, you can see text like following on console.
Manually set LLVM_ROOT to /usr/local/opt/emscripten/libexec/llvm/bin and comment out BINARYEN_ROOT in ~/.emscripten after running `emcc` for the first time.
Modified ~/.emscripten
I modified my ~/.emscripten
like this after calling emcc
once.
# this helps projects using emscripten find it EMSCRIPTEN_ROOT = os.path.expanduser(os.getenv('EMSCRIPTEN', '/usr/local/Cellar/emscripten/1.37.27/libexec')) # directory #LLVM_ROOT = os.path.expanduser(os.getenv('LLVM', '/usr/bin')) # directory LLVM_ROOT = os.path.expanduser(os.getenv('LLVM', '/usr/local/opt/emscripten/libexec/llvm/bin')) # directory # Manually set LLVM_ROOT to # /usr/local/opt/emscripten/libexec/llvm/bin # and comment out BINARYEN_ROOT # in ~/.emscripten after running `emcc` for the first time. # # BINARYEN_ROOT = os.path.expanduser(os.getenv('BINARYEN', '')) # if not set, we will use it from ports # If not specified, defaults to sys.executable.
Compile
In root directory of your project, run following.
# compile a specific file. rustc --target=wasm32-unknown-emscripten src/main.rs -o dist/main.js # build you project into wasm cargo build --target=wasm32-unknown-emscripten
My experience at Code Chrysalis
What is Code Chrysalis
Advanced Software Engineering School | Code Chrysalis | Tokyo, Japan
Code chrysalis is a coding bootcamp in Tokyo. We can learn modern web development for 3 month immersively. It is very difficult to join here if you have never learned programming. But during this course, you can be a full stack engineer with JavaScript even though you are not familiar with web development. And in this course, we communicate with others only in English.
The outline of this course is like following in my case. (10/09/2017 - 12/29/2017)
Before starting this program
- Finish pre-course
- Basic HTML, CSS, JavaScript
- Recursion
During this program
- Pair-programming
- Recursion
- Virtual DOM from Scratch
- Data structure
- Stack and queue
- Linked list
- Tree, Binary Tree
- Graph
- TDD and Test Doubles
- Async function
- callback
- Promises
- async/await
- ExpressJS
- Creating and Testing API,
- PostgreSQL
- GraphQL
- Outdoor activity. Learned modern style of development in real company.
- We went to Pivital.
- Redis
- Learning a other programming language than JavaScript (I chose Rust)
- Presentation in Public (https://www.meetup.com/ja-JP/CodeChrysalis/)
- React and Redux
- Refactoring others code
- CI/CD with Heroku CI
- Projects
- Solo-projects
- Team-projects
- Resume for job hunting
Morning activities
- Typing practice.
- Make a presentation.
- Algorithm practice. (Code coffee)
Others
- Homework everyday.
As you know from above information, we learn a lot of things everyday for 3 months. You need to make a decision of leaving current job if you want to join here and working at a company now. I know it's a big decision but after finishing this course, you would be a full stack engineer.
About me
- Free lance engineer.
- Self taught programmer
- Experience of programming for 6 years.
Why I joined Code Chrysalis
In my case, I wanted learn mainly communication in English and modern style of web development as a second priority.
In comparison to before joining here, I think my english has been improved but still have a week about listening part. But I learned even if my English is still poor but especially in development part, Ii is possible to communicate with others in only English because there are many words we already know as a programmer.
In learning modern development part, I got many knowledge I had not used such as GraphQL, React, Redux and so on. I mean I got great opportunity to learn many thing only for 3 months. I really appreciate it.
Conclusion
I recommend Code Chrysalis to people who really want to get web skills or want to become a full stack engineer. This course is not for beginner but my peers were beginner in web development. But most of them made it to the end of this program. If you have a passion of becoming a great engineer, you can be that like my peers.
My first public presentation.
- My experience.
- Targets of this article
- What unexpectedly easy was
- What unexpectedly difficult was
- Tips
- Conclusion. (What I learned. )
- Resources
My experience.
Needless to say, I was so nervous. It was my first presentation in public in English also I've nerver done any public presentations in Japanese. I spent a long time for preparing my slides(below) and a workshop material (below) and I had rehearsal for my presentation twice. I think it's kind of enough but I was feeling uncomfortable until the end of my presentation. So I want to share my experience of this If you think of doing presentation in your second language first time.
www.slideshare.net
Targets of this article
- People
- who have never made a presentation in public.
- who want to overcome your nervous in public speaking.
What unexpectedly easy was
Actually, I was uncomfortable until the end of my presentation. So I tried to talk with audience before I start it to make me calm and it works for me.
- People who I talked with looked smiley and I could have eye-contact to them many times.
- After finishing presentation, some people asked about what I taught in my presentation without feeling nervous.
What unexpectedly difficult was
I preapred lerning material for my workshop and wrote down how to install necessary environment to do the material. I thought most of them had already finished setting up environment but, It was opposite in real. So I had to change my original plan to demonstrate how to use the material to learn.
Tips
Be friendly
To remove your nervous, Being friendly to audience before you start is good way. For example, after having conversation with someone, he or she helps you during your presentation by smiling or asking some question.
Ask questions to audience.
When you forget what you want to say, it is better to ask questions to audience to avoid making silence. During the time, you can try to remember whant you are thinking about.
Make time for audience to introduce next to him or her.
This tip is related to Be friendly
. Some audience may come for the first time, which means audience might feel uncomfortable as well. Introducing themselves to others is kind of ice breaker. After introducing time, audience would have less nervous.
Conclusion. (What I learned. )
- Having conversation with audience before you start helps you.
- Unexpected things happen even though you spent a lot of time on preparing for your presentation. (At that time, you need to change your original plan.)
- If you are friendly, some people ask some questions without nervous.
Resources
Comparing variables, functions and class in Rust and JavaScript
- Before starting topic
- Targets of this article
- My experiences of Rust so far.
- Syntax
- Pros and cons
- Conclusion
- Resources
Before starting topic
I have just started to learn Rust and I hit the wall many times. Actually this blog is witten as a memo for me to remember and keep track of waht I learned so far.
First edition of this blog is might be lack of information for you. But I will append what I understand enough about Rust.
Targets of this article
- People who
- are also confused to Rust like me.
- don't know Rust and have interest in that.
- know syntax of JavaScript but don't know that of Rust.
My experiences of Rust so far.
Recently I got a oppotunity to learn new programming language that I never use. I spent about 30 minutes to decide one language from Go, Clojure, and Rust. The reason why I chose Rust was Just feeling.
After deciding Rust, I began to read documentation of Rust and search good example code/projects. I had only one week create a project with Rust and also shold make presentation with lecture. So I decided to create a API server for Todo application. I am now on project and using below tools.
- Rocket : Web framework for Rust.
- Diesel : ORM for Rust.
- serde : Serialization framework for Rust. Mainly using this for Handling JSON.
This blog is not for explaining how to create Todo application with Rust. From next section, I will write down Rust and JavaScript syntax as a comparison.
Syntax
Variable
When we create variable in Rust, let
keyword is used. JavaScript also has same keyword let
. But this let
keyword has different behavior. In JavaScript, let
keyword allow developer to overwrite the variable. But in Rust, That is not allowed except for using mut
keyword before variable name.
Example
// JavaScript let name = 'Alice'; // (Mutable) name = 'Bob'; // OK
// Rust let name = "Alice"; // (Immutable) // name = "Bob" // Error let mut name_2 = "Ace"; // (Mutable) name_2 = "Brian"; // OK
If you are familiar with JavaScript, You might know const
keyword
. let
in Rust without mut
keyword is similar to const
of JavaScript.
Function
In Rust, fn
is a keyword when creating a function instead of function
. Rust is a typed language so that you can put return type after ->
keyword.
JavaScript does not have this feature.
Using this functionality, Rust reduce potential bugs like other typed languages because compiler tells us invalid error if you return something value that is different from a type you set as a return type.
Example
// JavaScript function return_one() { return 1; }
// Rust // i32 is a data type that describe integer of 32bit. // Value without semicolon on last line means return value. // If you put semicolon like next example, compile error happens. fn return_one() -> i32 { 1 } fn return_one() -> i32 { 1; } // () after `->` describe void.(return nothing.) // So compile error happens in this code because types are does not match. (void and integer are different.) fn return_one() -> () { 1 }
struct, impl (== class of JavaScript)
You can write object in Rust with struct
keyword and also you can add method to the struct
value using impl
keyword. But methods has &self
as first argument like Perl
. If you are not familiar with this kind of rule, Maybe it is hard to imagine. Let's see the code how that code looks likes.
// JavaScript class Person { constructor(name) { this.name = name; } greet() { console.log(`My name is ${this.name}`); } } const person = new Person('Bob'); person.greet();
// Rust #[derive(Debug)] struct Person { name: String } impl Person { pub fn new(name: String) -> Person { Person {name: name} } pub fn greet(&self) -> () { println!("My name is {}", &self.name); } } let person = Person::new("Bob".to_string()); person.greet();
In this rust code, There are few keywords Derive
and "&
" that I have not explained. If you are familiar with C language, this &
describe reference same as pointer.
But this blog is just for kind of my memo. So I don't explain those for now. If you want to know more about Derive and "&
" below links might help you.
Pros and cons
Pros
- Blazingly fast(Rust page said that.)
Cons
- High learning curve because of strict syntax.
Conclusion
- Rust is a typed language.
- Rust has many tricky way and magic words for me.
- I try to update this blog appending what I understand enough about Rust.
Resources
Data flow of React and AngularJS
Targets of this article
- People who
- want to know what SPA is.
- want to know 2 types of data flow used by React and AngularJS.
My experiences of those.
First of all, I have been learning React recenly and I just know AngularJS a little but I do not have much expecrience of AngularJS. If there is something wrong, I would appriciate it if correcting me.
What is SPA?
SPA
stands for "Single Page Application". It means that literally a server provides only an HTML file and manipulates HTML elements using JavaScript.
React and AngularJS are powerful tool of SPA. If you do not use those kinds of libraries, you would be struggle with handling elements and data.
Data flow
As I learned, React applications mainly uses one way data flow. For example, above images describes following steps.
example
- Action: Click a button.
- Dispatcher: Event listener(callback function).
- Store: Update something and store some values.
- View: Update view (re-render.)
- Action: same as 1.
One way data flow is easy to understand how it works. React offers us a that kind of one way data flow library called Redux
. Redux flow is similar to previous one. Look at the below image.
From React Views, steps are following.
example
- Show React elements on a web page.
- User interactions such as clicking a button.
- By clicking a button, something action is called. In this case calling API.
- Web API/API Utils parts. After receiving response from API server, action calls disptch.
- If there is data from server,
Actions
pass data toStore
via callbacks that is executed by dispatcher. - Storing data and update React Views using stored new data.
Thanks to this flow, we just follow steps one by one.
Can we use redux on AngularJS?
My I answer about this question is Maybe yes
. In my understanding Redux
, that is just concepts of data flow, which means that is not for only react. Redux can be used any application even though the applications do not use react.
But, why is my answer Maybe yes
? Actually I tried AngularJS before like 2 or 3 yeas ago. At that time, AngularJS mainly use 2 way data binding in my comprehension of AngularJS.
Two way binding is other type of data flow in addition to one way data flow.
Above picture shows two-way data binding. Two-way data binding is that Each element has/connect a model and update each other interactively. For example, imagine a form
element. when form is populated some data, model also updates. On the other hand, when model is updated by something event or other elements, a element connected to the model also updates.
My opinion about React and AngularJS
I prefer one way data flow because of intuitive for me, which means the reason why I stop playing around AngularJS soon when I touched that.
According to my experience of AngularJS, The syntax of AngularJS is difficult to be familiar with it. AngularJS uses ng
attributes/syntaxes in HTML files. That is also one of points I do not want to use AngularJS. Comparing to AngularJS, React has JSX that looks HTML like style and it is easy to read for me.
Conclusion
- React and AngularJS are both powerful libraries of SPA.
- There are two styles of data flow.
- One-way data flow
- Two-way data binding.
- Both have unique syntax
- AngularJS: ng attributes that uses in HTML files.
- JSX: HTML like style and written in JSX file.
Postscripts
I found some articles and repositories that are about AngularJS with Redux. These are the recourses and added these in Resources
as well.
Resources
OverView of async/await
Targets of this article
- People who know "Promise" of JavaScript.
- People who want to know better way of writing async function than "Promise".
My experiences of "async/await"
I like "Promises" of JavaScript because we can write async function without Callback-Hell.
What if there is better writing style of async functions? That is async/await
. Before I knew async/await
, I had always used "Promises". But now, I prefer async/await
to Promises
. The reason why I prefer async/await
is that we can write async functions as if syncronous functions. It is much readable and organized.
Why should we know this?
As I already told you, async/await
allows us to write async functions that looks like syncronous style.
I prepared example code below that is written Promises
style and async/await
style. Let's have a look.
// ### Promises style ### function getFileDataByPromises() { return Promise.all([ readFile('/path/to/file1.json'), readFile('/path/to/file2.json'), readFile('/path/to/file3.json'), ]).then(results => { const data1 = results[0]; const data2 = results[1]; const data3 = results[2]; return buildDataWithFiles(data1, data2, data3); }).catch(err => { throw err; }); } // ### async/await style ### async function getFileDataByAsyncAwait() { const data1 = await readFile('/path/to/file1.json'); const data2 = await readFile('/path/to/file2.json'); const data3 = await readFile('/path/to/file3.json'); try { return buildDataWithFiles(file1, file2, file3); } catch(err) { throw err; } } // ### Helper functions const fs = require('fs'); function readFile(filePath) { return new Promise((resolve, reject) => { fs.readFile(filePath, 'utf-8', (err, data) => { if(err) { reject(err); } resolve(data); }); }); } function buildDataWithFiles(data1, data2, data3) { const buildData = []; // Something that combines file1, file2 and file3 // ... return buildData; }
How do you feel above code? Even though Promises
pattern looks good in comparison to Callback-Hell pattern, async/await
looks much better at least I think. In Promises
, we have to pass result data via then
method. If you want to add one more then
method and pass first result of Promises again, You should write it like below.
function getFileDataByPromises() { let data1, data2, data3; return Promise.all([ readFile('/path/to/file1.json'), readFile('/path/to/file2.json'), readFile('/path/to/file3.json'), ]).then(results => { data1 = results[0]; data2 = results[1]; data3 = results[2]; return buildDataWithFiles(data1, data2, data3); }).then(builtData => { // something process with data1, data2 and data3. // ... }).catch(err => { throw err; }); }
In above example code, values are assigned to the empty variables(data1, data2 and data3). This means that this code potentially have bugs because values are mutable and It is possible that values might not be our expected value.
On the other hand, async/await
style is much organized and stylish. We don't have to difine empty variable, which means we can use const
declaration. We can avoid unnecessary updating values and bug generated by update.
How to use async/await
Syntax
async function asyncFunction() { const resultOfPromise = await somethingProcessWithPromise(); }
From MDN page of await.
The await operator is used to wait for a Promise. It can only be used inside an async function.
- You can use
await
statement in functions withasync
declaration beforefunction
declaration. - When you put
await
operator before calling function, the function should return "promise" object.
Let's see the below image of example code. I wll explain what this code does after the image.
Example code
- Preparing functions.
- async function asyncFunction() {...}
- A function that use
async/await
- A function that use
- function somethingProcessWithPromise(){...}
- A function that returns promise object.
- async function asyncFunction() {...}
- Calling asyncFunction()
- Inside asyncFunction, I use
await
operator before"somethingProcessWithPromise()"
that returns promise object. resultOfPromise
variable will be assigned value whenresolve
ofpromise
is executed.- In this case
resultOfPromise
should be 'Hello!' becauseresolve
function takes 'Hello' as a argument.
- In this case
console.log
is not exuecuted until the value is assigned toresultOfPromise
variable.resolve
is executed after 1000 milliseconds with setTimeout.
- Inside asyncFunction, I use
- 'Hello!', 'Hi!' is output on the log.
Conclusion
- We can write async functions as if syncronous functions.
- To use
async/await
, we need to putasync
operator before function name andawait
operator before executing a function that returns promise object. await
operator can be inside only functions that is usedasync
operator.
Resources
"Promises" of JavaScript ~only 4 things what you should remember at least~
Targets of this article
- People who know fundamental of JavaScript.
- People who understand what a callback function(higher-order function) is and can use it.
- People who want to avoid Callback Hell.
My experiences about writing async functions.
When I used to write code with callback-hell pattern, The code was always messy and difficult to read even if that was my code. Before I knew Promises, I just wrote down async function with callback-hell style again and again. But after I learned promises, I started to be feel confortable to write async function because we can write code cleanly and the code will be more organized. So, If you do not know Promises so much, and you are suffering from writing async function, this article might help you from callback-hell.
The reason why you should use Promises.
When we need to write asyncronous functions, our code tend to be nested code. For example, let's see the below example code.
const fs = require('fs'); // ### Callback Hell Pattern ### function getComindedReviews(callback) { getDataWithCallback('/path/to/reviews.json', (err, reviews) => { if(err) throw err; getDataWithCallback('/path/to/products.json', (err, products) => { if(err) throw err; getDataWithCallback('/path/to/users.json', (err, users) => { if(err) throw err; const combindedReviews = buildReviews( reviews, products, users ); callback(combindedReviews); }); }); }); } // ### Promise Pattern ### function getComindedReviews() { return Promise.all([ getDataWithPromise('/path/to/reviews.json'), getDataWithPromise('/path/to/products.json'), getDataWithPromise('/path/to/users.json'), ]) .then((results) => { const reviews = results[0]; const products = results[1]; const users = results[2]; const combindedReviews = buildReviews( reviews, products, users ); return combindedReviews; }); } // ### Helper functions ### function getDataWithCallback(path, callback) { fs.readFile(path, 'utf-8', (err, data) => { if(err) { callback(err, null); return; } callback(null, data); }); } function getDataWithPromise(path) { return new Promise((resolve, reject) => { fs.readFile(path, 'utf-8', (err, data) => { if(err) { reject(err); } resolve(data); }) }); } function buildReviews(reviews, products, users) { return reviews.map((review) => { const product = products.filter(product => { return product.id === review.productId; }); const user = users.filter(user => { return user.id === review.userId; }); return { productName: product.name, userName: user.name, comment: review.comment, rating: review.rating }; }); }
This example shows 2 patterns with asyncronous functions.
- First one is using nested callback. (### Callback Hell Pattern ###)
- The other is using promises. (### Promise Pattern ###).
In this example, we read 3 files. You see that Callback pattern looks ugly and is hard to read. Imagine when we need read more files. The code is should be disaster. (nested and nested and nested and ...)
On the other hand, look at Promise pattern. Even if we read 100 files, nested level is still one. It is very easy to read and people can easily understand what this code does.
This is the biggest reason why we should use promises instead of callback-hell pattern. Code with promises when we use async functions is maintainable.
Main 4 things of Promises that help you.
If you remember these 4 things, you will be released from callback hell.
- Promise constructor
- Promise.prototype.then
- Promise.prototype.catch
- Promise.all
Promise constructor
Syntax
const promiseObject = new Promise((resolve, reject) => {});
- Promise constructor takes one callback function as an argument.
- the callback function has two arguments named
"resolve"
and"reject"
. Both"resolve"
and"reject"
are callback functions.- resolve
- To call
"resolve"
callback with data you want to pass when process finish successfully.- The data that
"resolve"
takes is passed to"then"
. I will explain it later in Promise.prototype.then section.
- The data that
- To call
- reject
- To call reject callback with error data when process fails.
- The error data that
"reject"
takes is passed to"catch"
. I will explain it later in Promise.prototype.catch section.
- The error data that
- To call reject callback with error data when process fails.
- resolve
Example code of Promise constructor
const promise = new Promise((resolve, reject) => { const data = getSomethingData(); if(data) { // If `data` variable has proper data => success resolve(data); } else { // If not, which means process failed. reject(new Error('process failed')); } });
Promise.prototype.then
Syntax
const promiseObject = new Promise((resolve, reject) => { resolve(data); }); promiseObject.then((data) => {});
- Promise object has
"then"
method which takes an argument of callback function. - The callback function receives an argument that is passed from
"resolve"
function I explained in previous section or"return"
statement previous then method. (I will write example code about previous"then"
method.) "then"
method returns a new promise object, which means we can use"then"
method after other promise's"then"
method. We call it"method chaining"
.
Example code of Promise constructor
Promise.prototype.catch
Syntax
const promiseObject = new Promise((resolve, reject) => { reject(error); }); promiseObject .then((data) => {}) .catch((error) => {});
- Promise object has
"catch"
method which takes a callback function that takes an argument that is usually an error object. - A
"catch"
method is executed when"reject"
callback function in Promise constructor is called or Error is thrown.
Example code of Promise constructor
Pattern 2 (When error is thrown from Promise Constructor.)
Pattern 3 (When error is thrown from "then"
method.)
Promise.all
Syntax
const p1 = new Promise((resolve, reject) => { resolve(data); }); const p2 = new Promise((resolve, reject) => { resolve(data); }); const p3 = new Promise((resolve, reject) => { resolve(data); }); const promiseObjects = [p1, p2, p3]; Promise.all(promiseObjects) .then((dataList) => {}) .catch((error) => {});
"Promise.all"
takes an array of promises."then"
method receives an array that has each result of promise objects , in this case p1, p2 and p3, in same order that we put promiseObjects(p1, p2, p3) into array as an argument of Promise.all.- If
"promiseObjects"
that"Promise.all"
takes has at least one error,"catch"
method is executed insted of"then"
method.
Example code of Promise constructor
Pattern 1 (When all promise objects succeeded.)
Pattern 2 (When at least one promise object failed.)
Conclusion
- Callback hell makes us suffering understanding what the code does.
- Promises enable us to organize code neater and better.
- What you should remember about Promises are only 4 things.
- Promise constructor
- Promise.prototype.then
- Promise.prototype.catch
- Promise.all