'Programming'에 해당되는 글 1632건

  1. 2023.05.26 rust mut 외 몇가지 컴파일 에러들
  2. 2023.05.25 rust mut
  3. 2023.05.25 rust visibility and privacy
  4. 2023.05.24 golang waitgroup
  5. 2023.05.24 golang echo server middleware
  6. 2023.05.24 golang 동시성
  7. 2023.05.20 rust was
  8. 2023.05.18 webGPU
  9. 2023.05.16 golang 고루틴과 채널
  10. 2023.05.16 golang switch, select
Programming/rust2023. 5. 26. 23:31

use std::io; 없이 사용시

error[E0433]: failed to resolve: use of undeclared crate or module `io`
 --> main.rs:8:5
  |
8 |     io::stdin()
  |     ^^
  |     |
  |     use of undeclared crate or module `io`
  |     help: a builtin type with a similar name exists: `i8`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0433`.




변수 사용 없음 (경고)

warning: unused `Result` that must be used
  --> main.rs:10:5
   |
10 | /     io::stdin()
11 | |         .read_line(&mut guess);
   | |______________________________^
   |
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: `#[warn(unused_must_use)]` on by default

warning: 1 warning emitted




read_line mut 없이

error[E0308]: mismatched types
  --> main.rs:11:20
   |
11 |         .read_line(&guess);
   |          --------- ^^^^^^ types differ in mutability
   |          |
   |          arguments to this method are incorrect
   |
   = note: expected mutable reference `&mut String`
                      found reference `&String`
note: method defined here
  --> /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc\library\std\src\io\stdio.rs:383:12

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.





///
let guess = String::new();
    io::stdin().read_line(&mut guess);
///

error[E0596]: cannot borrow `guess` as mutable, as it is not declared as mutable
  --> main.rs:11:20
   |
11 |         .read_line(&mut guess);
   |                    ^^^^^^^^^^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
8  |     let mut guess = String::new();
   |         +++

error: aborting due to previous error

For more information about this error, try `rustc --explain E0596`.







//
let guess = String::new();
    io::stdin().read_line(&guess);
//

error[E0308]: mismatched types
 --> main.rs:9:27
  |
9 |     io::stdin().read_line(&guess);
  |                 --------- ^^^^^^ types differ in mutability
  |                 |
  |                 arguments to this method are incorrect
  |
  = note: expected mutable reference `&mut String`
                     found reference `&String`
note: method defined here
 --> /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc\library\std\src\io\stdio.rs:383:12

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.










'Programming > rust' 카테고리의 다른 글

rust mut  (0) 2023.05.25
rust visibility and privacy  (0) 2023.05.25
rust was  (0) 2023.05.20
c에서 rust 호출하기  (0) 2023.05.11
rust 실행파일  (0) 2023.05.11
Posted by 구차니

댓글을 달아 주세요

Programming/rust2023. 5. 25. 19:53

변수에 값을 넣으면 c 처럼 값이 변경되지 않아

let을 이용 재귀적으로 다시 할당을 하거나 mut 키워드로 변경이 가능한 변수로 지정해야 한다.

fn main() {
    let x = 5;
    println!("The value of x is: {x}");
    x = 6;
    println!("The value of x is: {x}");
}

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:4:5
  |
2 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: consider making this binding mutable: `mut x`
3 |     println!("The value of x is: {x}");
4 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` due to previous error

 

좀 더 아래 shadowing 에 있는 예제인데

let x = 5;

let x = x + 1; 을 이용해서 자기 자신에게 새로운 값을 소유하게 하는 것은 인정 되는 듯

fn main() {
    let x = 5;

    let x = x + 1;

    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {x}");
    }

    println!("The value of x is: {x}");
}

 

아무튼 언어 설계상 정석은 mut 키워드를 쓰는 것으로 보인다.

fn main() {
    let mut x = 5;
    println!("The value of x is: {x}");
    x = 6;
    println!("The value of x is: {x}");
}

 

[링크 : https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html]

'Programming > rust' 카테고리의 다른 글

rust mut 외 몇가지 컴파일 에러들  (0) 2023.05.26
rust visibility and privacy  (0) 2023.05.25
rust was  (0) 2023.05.20
c에서 rust 호출하기  (0) 2023.05.11
rust 실행파일  (0) 2023.05.11
Posted by 구차니

댓글을 달아 주세요

Programming/rust2023. 5. 25. 19:40

pub 이라는 키워드가 존재해서

Syntax
Visibility :
      pub
   | pub ( crate )
   | pub ( self )
   | pub ( super )
   | pub ( in SimplePath )

 

기본은 private 이고 public으로 할 녀석들만 pub로 해주면 된다.

그런데 rust는 객체지향 언어는 아니라니까 class가 존재하지 않는데

c언어 처럼 static 키워드로 내/외부용으로 구분하는 수준이 되려나?

구조체에서 개별 항목에 대해서 pub이 적용되는지 조금 더 찾아봐야 할 것 같다.

// Declare a private struct
struct Foo;

// Declare a public struct with a private field
pub struct Bar {
    field: i32,
}

// Declare a public enum with two public variants
pub enum State {
    PubliclyAccessibleState,
    PubliclyAccessibleState2,
}

[링크 : https://doc.rust-lang.org/reference/visibility-and-privacy.html]

'Programming > rust' 카테고리의 다른 글

rust mut 외 몇가지 컴파일 에러들  (0) 2023.05.26
rust mut  (0) 2023.05.25
rust was  (0) 2023.05.20
c에서 rust 호출하기  (0) 2023.05.11
rust 실행파일  (0) 2023.05.11
Posted by 구차니

댓글을 달아 주세요

Programming/golang2023. 5. 24. 16:10

고루틴이 종료되는 시점을 확인하는 방법으로 보면 되려나?

 

여러개의 고루틴을 종료할때 까지 기다리기 위해  wait gorup을 이용할 수 있다.

package main

import (
    "fmt"
    "sync"
    "time"
)

func worker(id int) {
    fmt.Printf("Worker %d starting\n", id)

    time.Sleep(time.Second)
    fmt.Printf("Worker %d done\n", id)
}

func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)

        i := i

        go func() {
            defer wg.Done()
            worker(i)
        }()
    }

    wg.Wait()

}

[링크 : https://gobyexample.com/waitgroups]

[링크 : https://pyrasis.com/book/GoForTheReallyImpatient/Unit35/06]

[링크 : https://pkg.go.dev/sync#WaitGroup.Add]

'Programming > golang' 카테고리의 다른 글

golang echo server middleware  (0) 2023.05.24
golang 동시성  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
golang switch, select  (0) 2023.05.16
golang uds  (0) 2023.05.16
Posted by 구차니

댓글을 달아 주세요

Programming/golang2023. 5. 24. 15:41

golang의 echo를 이용해서 웹서버 만드는건 쉬운데

서버 돌려 두면 별도의 go routine으로 돌테니 어떻게 구성을 해야

IPC를 통해 받은 변수를 깨지지 않게 처리할 수 있을까?

 

걍 결론은.. mutex로 귀결인가?

func (s *Stats) Handle(c echo.Context) error {
s.mutex.RLock()
defer s.mutex.RUnlock()
return c.JSON(http.StatusOK, s)
}

func main() {
e := echo.New()

// Debug mode
e.Debug = true

//-------------------
// Custom middleware
//-------------------
// Stats
s := NewStats()
e.Use(s.Process)
e.GET("/stats", s.Handle) // Endpoint to get stats

// Server header
e.Use(ServerHeader)

// Handler
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})

// Start server
e.Logger.Fatal(e.Start(":1323"))
}

[링크 : https://echo.labstack.com/cookbook/middleware/]

'Programming > golang' 카테고리의 다른 글

golang waitgroup  (0) 2023.05.24
golang 동시성  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
golang switch, select  (0) 2023.05.16
golang uds  (0) 2023.05.16
Posted by 구차니

댓글을 달아 주세요

Programming/golang2023. 5. 24. 15:38

atomic 패키지는 특정 변수의 값 증가등에 대해서 atomic operation 해주는 것 같고 copy는 없는 것 같고

sync.mutex가 역시 가장 무난한 선택인가 싶다.

channel은 내가 원하는 패키지에서 사용가능한 방법은 아난 것 같군..

 

atomic > mutex > channel

[링크 : https://woojinger.tistory.com/100]

[링크 : https://dev-yakuza.posstree.com/ko/golang/goroutine/]

[링크 : https://pkg.go.dev/sync/atomic]

'Programming > golang' 카테고리의 다른 글

golang waitgroup  (0) 2023.05.24
golang echo server middleware  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
golang switch, select  (0) 2023.05.16
golang uds  (0) 2023.05.16
Posted by 구차니

댓글을 달아 주세요

Programming/rust2023. 5. 20. 13:48

'Programming > rust' 카테고리의 다른 글

rust mut  (0) 2023.05.25
rust visibility and privacy  (0) 2023.05.25
c에서 rust 호출하기  (0) 2023.05.11
rust 실행파일  (0) 2023.05.11
rust if문  (0) 2023.05.11
Posted by 구차니

댓글을 달아 주세요

Programming/web 관련2023. 5. 18. 14:14

유튜브에서 노마드 코더의 추천영상에 webGPU라는게 떠서 찾아보니

겁나 따끈한(고작 8일 지난..) 표준이다.

 

WebGPU
W3C Working Draft, 10 May 2023

[링크 : https://www.w3.org/TR/webgpu/]

[링크 : https://codelabs.developers.google.com/your-first-webgpu-app?hl=ko#0]

 

크롬94 베타 부터 webgpu 지원이 시작되었다는데(일단 글은 2021.09.11)

[링크 : https://www.clien.net/service/board/park/16489505]

 

webGL을 물리치고 대세가 될지 아니면 병행하게 될지 미래가 궁금해진다.

윈10 + 크롬 버전 113.0.5672.93(공식 빌드) (64비트)

 

ubuntu 18.04 + 버전 113.0.5672.126(공식 빌드) (64비트)

[링크 : https://webgpu.github.io/webgpu-samples/samples/shadowMapping]

 

+

리눅스에서는 webGPU가 disable인데.. 이걸 어떻게 켤 수 있으려나?

chrome://gpu/

 

[링크 : https://discourse.threejs.org/t/webgpu-example-not-working-in-ubuntu-20-04/40484]

Posted by 구차니

댓글을 달아 주세요

Programming/golang2023. 5. 16. 15:39

채널의 경우 1개로 해두면 하나가 들어갈 때 까지 해당 위치에서 블로킹 된다.

아래 예제는 받는 부분을 삭제했는데 그렇기에 채널을 통해 전송은 되지만 수신하지 않아 비워지지 않기 때문에

one을 출력하지 못하고 멈춰있는 것을 확인할 수 있다.

package main

import (
f "fmt"
"time"
)

func main() {

f.Println("select")

c1 := make(chan string)
c2 := make(chan string)

go func() {
time.Sleep(time.Second * 1)
f.Println("---")
c1 <- "one"
f.Println("one")
c1 <- "two"
f.Println("two")
c1 <- "three"
f.Println("three")
c1 <- "four"
f.Println("four")
}()

go func() {
time.Sleep(time.Second * 2)
c2 <- "fifth"
}()

for i := 0; i < 10000000000; i++ {
time.Sleep(time.Second)
}

}
$ go run go.go 
select
---
^Csignal: interrupt

 

다만, make를 통해 채널 버퍼를 n개로 만들어 두면, 넣을 수 있는 동안은 넣고 블로킹 되지 않고 넘어갈 수 있다.

package main

import (
f "fmt"
"time"
)

func main() {

f.Println("select")

c1 := make(chan string, 4)
c2 := make(chan string)

go func() {
time.Sleep(time.Second * 1)
f.Println("---")
c1 <- "one"
f.Println("one")
c1 <- "two"
f.Println("two")
c1 <- "three"
f.Println("three")
c1 <- "four"
f.Println("four")
}()

go func() {
time.Sleep(time.Second * 2)
c2 <- "fifth"
}()

for i := 0; i < 10000000000; i++ {
time.Sleep(time.Second)
}

}
$ go run go.go 
select
---
one
two
three
four
^Csignal: interrupt

 

[링크 : https://judo0179.tistory.com/88]

'Programming > golang' 카테고리의 다른 글

golang echo server middleware  (0) 2023.05.24
golang 동시성  (0) 2023.05.24
golang switch, select  (0) 2023.05.16
golang uds  (0) 2023.05.16
golang mutex (sync)  (0) 2023.05.16
Posted by 구차니

댓글을 달아 주세요

Programming/golang2023. 5. 16. 11:32

golang switch는 신형 언어에 확장되서 그런가 꽤나 만능이다.

특이하게 조건식도 가능하고, 케이스 리스트도 된다.(c#에서 얼핏 봤던 느낌..)

package main

import (
"fmt"
"time"
)

func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}

[링크 :https://go.dev/tour/flowcontrol/11]

 

func WhiteSpace(c rune) bool {
switch c {
case ' ', '\t', '\n', '\f', '\r':
return true
}
return false
}

[링크 : https://hamait.tistory.com/1017]

 

아무튼 select는 channel 처리에 좀더 특화된 구문으로 생긴것 자체는 switch - case와 동일하게 작성된다.

다만, 동시에 여러개가 들어왔을 경우 랜덤하게 실행된다고 한다.

(생각이 꼬였는지 동시에 들어오면 가장 위에꺼 부터 실행되어야 하는거 아냐? 싶은데 동시성이니까 랜덤하게 처리되는건가..)

The select statement lets a goroutine wait on multiple communication operations.

A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

 

package main

import "fmt"

func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}

func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}

[링크 : https://go.dev/tour/concurrency/5]

 

[링크 : https://edu.goorm.io/learn/lecture/2010/한-눈에-끝내는-고랭-기초/lesson/382961/채널-select문]

 

'Programming > golang' 카테고리의 다른 글

golang 동시성  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
golang uds  (0) 2023.05.16
golang mutex (sync)  (0) 2023.05.16
go 포맷터  (0) 2023.05.11
Posted by 구차니

댓글을 달아 주세요