I have a single main.rs file. When I compile it by cargo run, I get an error:
error: linking with `cc` failed: exit status: 1
= note: ld: library not found for -lgtk-3
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I wanted to make a new window with titled "hello world". But when I run the program it gives me this error
I've seen some topic related to this one but none of them helped me to solve the problem.
My code:
extern crate gtk;
use gtk::*;
pub struct Application {
pub window: Window,
pub header: Header,
}
pub struct Header {
pub container: HeaderBar,
}
impl Application {
fn new() -> Application {
let window = Window::new(WindowType::Toplevel);
let header = Header::new();
window.set_titlebar(&header.container);
window.set_title("Простая программа");
window.set_wmclass("simple-gtk", "Простая программа");
Window::set_default_icon_name("имя иконки");
window.connect_delete_event(move |_, _| {
main_quit();
Inhibit(false)
});
Application { window, header }
}
}
impl Header {
fn new() -> Header {
let container = HeaderBar::new();
container.set_title("Простая программа");
container.set_show_close_button(true);
Header { container }
}
}
fn main() {
if gtk::init().is_err() {
eprintln!("Не удалось инициализировать GTK приложение.");
return;
}
let app = Application::new();
app.window.show_all();
gtk::main();
}
My cargo.toml
[package]
name = "hello_world"
version = "0.1.0"
authors = ["Yura Martyr"]
[dependencies]
[dependencies.gtk]
version = "0.3.0"
features = ["v3_22"]
Related
I am learning Rust. This is the code I'm running
Struct Object {
width: u32,
height:u32,
}
impl Object {
fn area(&slef) --> u32 {
}
fn new(width: u32, height: u32) --> Object {
Object {
width,
height,
}
}
}
fn main() {
let o = Object {
width: 35,
height: 55,
};
let obj = Object ::new(57,83);
println!("{}x{} with area: {}", o.width, o.height, o.area());
println!("{}x{} with area: {}", obj.width, obj.height, obj.area());
This the error I receive. Any help would be greatly appreciated.
PS C:\Users\Jessica\play_ground> cargo new play_ground --bin
warning: compiling this new package may not work due to invalid workspace configuration
failed to parse manifest at `C:\Users\Jessica\Cargo.toml`
Caused by:
no targets specified in the manifest
either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present
Created binary (application) `play_ground` package
PS C:\Users\Jessica\play_ground> cargo run
error: failed to parse manifest at `C:\Users\Jessica\Cargo.toml`
Caused by:
no targets specified in the manifest
either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present
PS C:\Users\Jessica\play_ground
Your code have some syntax errors, should be something like this
struct Object {
width: u32,
height:u32
}
impl Object {
fn area(&self) -> u32 {
self.width * self.height
}
fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
}
}
}
fn main() {
let o = Object {
width: 35,
height: 55,
};
let obj = Object ::new(57,83);
println!("{}x{} with area: {}", o.width, o.height, o.area());
println!("{}x{} with area: {}", obj.width, obj.height, obj.area());
}
You can try it in playgound online https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1c4f18874d42608a35b7e825aaf19619
Or in your computer you run:
cargo init atest
cd atest
[code, notepad, or your prefer editor] src/main.rs "update main.rs
cargo run
I’m trying to write a client to communicate with my grpc server written with tonic using Rust, but I’m having trouble understanding where to define and connect to the client, thus getting errors with my import statement. I’ve followed several tutorials and am having trouble finding information on how to create and import a client. My error is:
error[E0432]: unresolved import `user::client`
--> user/src/client.rs:2:36
|
2 | use user::client::{UserClient};
| ^^^^^^ could not find `client` in `user`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0432`.
error: could not compile `user`
In my proto.rs file:
syntax = "proto3";
package user;
message CreateUser {
string name = 1;
}
[package]
name = "user"
version = "0.1.0"
edition = "2018"
[lib]
[[bin]]
name = "server"
path = "src/server.rs"
[[bin]]
name = "client"
path = "src/client.rs"
[dependencies]
tonic = "0.5"
prost = "0.8"
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
tonic-build = "0.5"
My lib.rs file:
pub mod user {
tonic::include_proto!("user");
}
pub mod server;
pub mod client{
tonic::include_proto!("user");
}
main.rs:
use user::server;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!(message = "Started user server");
server::start_server().await?;
Ok(())
}
client.rs:
use user::{UserRequest };
use user::client::{UserClient}; // what should this import be, where does the client et created?
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = UserClient::connect("http://[::1]:50051").await?; // how do I create UserClient
let request = tonic::Request::new(UserRequest {
id: "1".into(),
});
println!("Sending request to gRPC Server...");
let response = client.create_user(request).await?;
println!("RESPONSE={:?}", response);
Ok(())
}
For reference, I’m following:
https://tjtelan.com/blog/lets-build-a-single-binary-grpc-server-client-with-rust-in-2020/
https://blog.logrocket.com/rust-and-grpc-a-complete-guide/
https://dev.to/anshulgoyal15/a-beginners-guide-to-grpc-with-rust-3c7o
I am getting a compiler error trying to use the log crate in a package in a workspace. The other crates in the workspace are using logging without problem.
Cargo.toml:
[dependencies]
log = "^0"
rocket = "^0"
[dependencies.uuid]
version = "^0"
features = ["v4"]
lib.rs:
#![feature(proc_macro_hygiene, decl_macro)]
use rocket::{
Request,
Data,
Response
};
use rocket::request::{
self,
FromRequest,
Outcome
};
use rocket::fairing::{
Fairing,
Info,
Kind
};
use uuid::Uuid;
use std::fmt;
use log;
pub struct LoggerFairing {
service_name: &'static str
}
impl LoggerFairing {
pub fn new(service_name: &'static str) -> Self {
LoggerFairing {
service_name
}
}
}
impl Fairing for LoggerFairing {
fn info(&self) -> Info {
Info {
name: self.service_name,
kind: Kind::Request | Kind::Response
}
}
fn on_request(&self, req: &mut Request, _: &Data) {
let ip_addr = req.client_ip().map(|addr| addr.to_string())
.unwrap_or("IP Address unknown".to_string());
let method = req.method();
let url = req.uri();
let request_id = get_request_id(req);
log::info!("request {:?} from {}: {} {}", request_id, ip_addr, method, url);
}
fn on_response(&self, req: &Request, res: &mut Response) {
let request_id = get_request_id(req);
let status = res.status();
log::info!("request {:?} responded with {}", request_id, status);
}
}
fn get_request_id<'t, 'r>(req: &'t Request<'r>) -> Option<RequestId<'t>> {
match req.guard::<RequestId>() {
Outcome::Success(request_id) => Some(request_id),
_ => None
}
}
pub struct RequestId<'t> {
pub id: &'t Uuid
}
impl<'t, 'r> FromRequest<'t, 'r> for RequestId<'t> {
type Error = ();
fn from_request(req: &'t Request<'r>) -> request::Outcome<Self, Self::Error> {
let id = req.local_cache(|| Uuid::new_v4());
request::Outcome::Success(RequestId {
id
})
}
}
impl<'t> fmt::Display for RequestId<'t> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.id)
}
}
The error message:
error: cannot find macro `log` in this scope
--> utils\logging\src\lib.rs:62:9
|
62 | log::info!("request {:?} from {}: {} {}", request_id, ip_addr, method, url);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: cannot find macro `log` in this scope
--> utils\logging\src\lib.rs:71:9
|
71 | log::info!("request {:?} responded with {}", request_id, status);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 2 previous errors
error: could not compile `logging`.
I've used several variations of the use log statement and how I'm calling the info! macro, but they all cause the same error message. I've tried specifying exact versions in Cargo.toml.
I'm stumped. This is exactly how I'm using log in other crates.
Specifying the exact version of the log crate (0.4.11) in Cargo.toml fixes this problem.
I'm assuming there is something funny happening when Cargo tries to resolve the dependencies.
So I'm new to Rust and tinkering with some code to read a config file with nested values and while I seem to have the data, I'm just not sure how to get to the inner values. Am I returning it wrong or is there some simple way to access this struct I'm missing?
This compiles and shows the values properly nested, but I don't seem to be able to reach inside the Ok() wrapper. Even just a page number I should be reading in "The Book" would help.
Cargo.toml
[dependencies]
dirs = "2.0"
config = "0.10"
serde = "1.0"
serde_derive = "1.0"
main.rs
extern crate dirs;
extern crate config;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use config::{ConfigError, Config, File};
#[derive(Debug, Deserialize)]
struct N4_env_conf {
debug: bool,
thingy: String,
blue: String,
}
#[derive(Debug, Deserialize)]
struct N4_conf {
local: N4_env_conf,
dev: N4_env_conf,
prod: N4_env_conf,
}
impl N4_conf {
pub fn new() -> Result<Self, ConfigError> {
let mut s = Config::new();
s.merge(File::with_name("Settings"))?;
s.try_into()
}
}
fn main() {
let config_dir = format!("{}/.config/n4_config", dirs::home_dir().unwrap().display().to_string());
let settings = N4_conf::new();
println!("{:?}", config_dir);
println!("{:#?}", settings);
}
Settings.toml
[local]
debug = true
thingy = "somethingy"
blue = "greenish"
[dev]
debug = true
thingy = "something"
blue = "green"
[prod]
debug = false
thingy = "otherthing"
blue = "red"
The variable settings has the type Result<N4_conf, ConfigError>. That variable may contain a value of type N4_conf or an error of type ConfigError, dependent on the outcome of N4_conf::new().
Example:
match settings {
Ok(conf) => {
println!("local = {:#?}", conf.local);
assert_eq!(conf.local.debug, true);
println!("local.debug = {:?}", conf.local.debug);
println!("local.thingy = {:?}", conf.local.thingy);
println!("local.blue = {:?}", conf.local.blue);
println!("dev = {:#?}", conf.dev);
println!("dev.debug = {:?}", conf.dev.debug);
assert_eq!(conf.dev.debug, true);
println!("dev.thingy = {:?}", conf.dev.thingy);
println!("dev.blue = {:?}", conf.dev.blue);
println!("prod = {:#?}", conf.prod);
assert_eq!(conf.prod.debug, false);
println!("prod.debug = {:?}", conf.prod.debug);
println!("prod.thingy = {:?}", conf.prod.thingy);
println!("prod.blue = {:?}", conf.prod.blue);
}
Err(e) => {
panic!(e);
}
}
See:
https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
What's the benefit of using a Result?
So thank to #0x64 for trying to help you were definitely closer to the solution than I was when I posted this. My issue was mainly just me trying to follow an example in the source repo for "config" too closely. The solution was to handle the Result inside the constructor method and change the return type to Self. My struct method changed to this and it behaves as I expected:
impl N4_conf {
pub fn new() -> Self {
let mut s = Config::new();
s.merge(File::with_name("Settings")).expect("Problem loading config file");
match s.try_into() {
Ok(conf) => {
conf
}
Err(e) => {
println!("{:?}", e);
panic!(e);
}
}
}
}
When it works, this performs perfectly returning a Struct I can access normally like so:
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/config-playground`
"/home/kill-all-humans/.config/n4_config"
N4_conf {
local: N4_env_conf {
debug: true,
thingy: "somethingy",
blue: "greenish",
},
dev: N4_env_conf {
debug: true,
thingy: "something",
blue: "green",
},
prod: N4_env_conf {
debug: false,
thingy: "otherthing",
blue: "red",
},
}
My next problem is this does not work at all consistently. There appears to be an intermitten bug in processing hierarchical config files in the "config" crate. Such that 50% of the time I get this instead, with zero code changes or rebuilds:
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/config-playground`
missing field `local`
thread 'main' panicked at 'Box<Any>', src/main.rs:35:17
stack backtrace:
0: backtrace::backtrace::libunwind::trace...
To which the "missing field" is literally whatever the first field in the N4_conf struct is. I haven't dug into it deeply, but I think I'll skip this crate and just go back to dotenv.
I haven't used the Config module as I switched to toml for my main configuration files. It does support all features from ini files and some more. You might want to have a look. Here is how I use it
Why do I get a compilation failure in this elementary program?
use std::thread;
fn main() {
for i in 1..10 {
let _ = thread::scoped( move || {
println!("hello from thread {}", i);
});
}
}
I try to build the program and I get:
src/main.rs:5:17: 5:36 error: unresolved name `thread::scoped`
src/main.rs:5 let _ = thread::scoped( move || {
^~~~~~~~~~~~~~~
Why?
The version of Rust I use:
$ rustc --version
rustc 1.0.0-nightly (170c4399e 2015-01-14 00:41:55 +0000)
The problem indeed was with the version of the rustc.
After upgrade the program was successfully compiled:
Compiling examples v0.0.1 (file:///home/igor/rust/projects/examples)
src/main.rs:1:5: 1:16 warning: unused import, #[warn(unused_imports)] on by default
src/main.rs:1 use std::thread;
^~~~~~~~~~~
The warning disappeared after I removed use:
fn main() {
for i in 1..10 {
let _ = thread::scoped( move || {
println!("hello from thread {}", i);
});
}
}
(Thank you, huon-dbaupp and Dogbert, for your help).