Rust Error failed to parse manifest no targets specified - rust

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

Related

Can't run an installed program using std::process::Command

I'm writing a small CLI app to set up my development environment based on a Jira ticket, currently I'm trying to open VS Code but I get a command not found error even though I can open VS Code from withing my terminal.
// jira.rs
use std::fmt;
pub struct JiraTicket {
pub key: String,
pub number: u32,
}
impl JiraTicket {
pub fn new(key: String, number: u32) -> JiraTicket {
JiraTicket { key, number }
}
}
impl fmt::Display for JiraTicket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{}", self.key, self.number)
}
}
// command.rs
pub fn open_vscode(ticket: Option<&JiraTicket>) {
let path = match ticket {
Some(path) => path.to_string(),
None => ".".to_string(),
};
let vscode_command = Command::new("code")
.arg(path)
.status()
.expect("An error ocurred while opening vs code");
if vscode_command.success() {
println!("{}", "Opened VSCode".green());
} else {
println!("{}", "Failed to open VSCode".red());
}
}
I already looked at:
Command not found when using std::process::command in rust?
Unable to use std::process::Command - No such file or directory
"code.cmd" seems to work:
let vscode_command = Command::new("code.cmd")
.arg(path)
.status()
.expect("An error ocurred while opening vs code");
I'm not sure why "code.cmd" works but "code" doesn't, though.
Might be related to rust-lang issue #37519.

How do I add resources such as text files or exe files into my application?

I tried this code
static HOST_FILE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png");
fn main() {
let host_str = std::str::from_utf8(HOST_FILE). unwrap();
println!("Hosts are:\n{}", &host_str[..42]);
}
But it shows me an error:
thread 'main' panicked at 'called Result::unwrap() on an Err value: Utf8Error { valid_up_to: 66, error_len: Some(1) }', src\main.rs:48:51
stack backtrace
static IMAGE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png");
fn main() {
println!("Image: {:?}", IMAGE);
}
Although I recommend using a path relative to your source code, like
static IMAGE: &'static [u8] = include_bytes!("../cbimage.png");
fn main() {
println!("Image: {:?}", IMAGE);
}
And place cbimage.png next to your Cargo.toml.

error: linking with `cc` failed: exit status: 1 on Mac m1

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"]

Rust how do I get to the inner nested structs parsed out of a config file in Rust config crate

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

How do I fix a segfault when the lifetime of a dynamically loaded library expires?

I'm using the following scheme:
Start the main program.
Dynamically load / unload necessary libraries without interrupting the main program.
The main program terminates.
All of the code (the main program, the dynamic library) is written in Rust and it is all compiled with -Cprefer-dynamic.
The dynamic library contains a Plugin struct that implements the plugin::Plugin trait with a new function that returns a boxed trait object (plugin::Plugin).
Dynamic library example:
#[derive(Debug)]
pub struct Plugin;
impl Plugin {
#[no_mangle]
pub fn new() -> Box<plugin::Plugin> {
println!("IN NEW!");
Box::new(Plugin)
}
}
impl plugin::Plugin for Plugin {
fn test(&mut self) -> plugin::Result<()> {
println!("IN TEST!");
Ok(())
}
}
plugin::Plugin is a trait:
pub trait Plugin: Debug {
fn test(&mut self) -> Result<()>;
}
Main program:
fn main() {
env_logger::init().unwrap();
info!("[MAIN]<-");
if let Ok(mut plugins) = load(Path::new("plugins/")) {
for (path, plugin) in plugins.iter_mut() {
debug!("path: {:?}, plugin: {:?}", path, plugin);
plugin.plugin.test();
}
thread::sleep(Duration::from_secs(30));
// <- as soon as the plugins is beyond his lifetime, segmentation fault.
}
info!("[MAIN]->");
}
fn load(path: & Path) -> Result<HashMap<String, Plugin>> {
let mut plugins = HashMap::new();
let valid_extensions: [& OsStr; 3] = ["dylib".as_ref(), "so".as_ref(), "dll".as_ref()];
for dir_entry in try!(path.read_dir()) {
let path = try!(dir_entry).path();
if path.extension().is_none() || !valid_extensions.contains(& path.extension().unwrap()) {
warn!("invalid dynamic library extension; extension: {:?}", path.extension());
continue
}
let key = path.clone().into_os_string().into_string().unwrap();
let lib = DynamicLibrary::open(Some(& path)).unwrap();
let new: extern fn() -> Box<plugin::Plugin> = unsafe {
std::mem::transmute(lib.symbol::<u8>("new").unwrap())
};
let plugin = Plugin {
_lib: lib,
plugin: new(),
};
plugins.insert(key.clone(), plugin);
}
Ok(plugins)
}
struct Plugin {
_lib: DynamicLibrary,
pub plugin: Box<plugin::Plugin>,
}
Is it even correct to use FFI for this type of Rust-Rust interaction?

Resources