Go 语言代码示例,用于实现一个简单的社交媒体平台:
package main
import (
"fmt"
"strings"
"time"
)
type User struct {
ID int
Username string
Email string
Followers []int
}
type Post struct {
ID int
Content string
Timestamp time.Time
UserID int
}
type SocialMediaPlatform struct {
Users map[int]User
Posts []Post
}
func main() {
socialMedia := SocialMediaPlatform{
Users: make(map[int]User),
Posts: []Post{},
}
// 添加一些用户
socialMedia.addUser(User{
ID: 1,
Username: "user1",
Email: "[email protected]",
})
socialMedia.addUser(User{
ID: 2,
Username: "user2",
Email: "[email protected]",
})
// 发布一些帖子
socialMedia.addPost(Post{
ID: 1,
Content: "Hello, World!",
Timestamp: time.Now(),
UserID: 1,
})
socialMedia.addPost(Post{
ID: 2,
Content: "This is a sample post.",
Timestamp: time.Now(),
UserID: 2,
})
// 显示所有用户的帖子
for _, user := range socialMedia.Users {
fmt.Println(user.Username, "的帖子:")
posts := socialMedia.getUserPosts(user.ID)
for _, post := range posts {
fmt.Println(post.Content)
}
fmt.Println()
}
}
func (sm *SocialMediaPlatform) addUser(user User) {
sm.Users[user.ID] = user
}
func (sm *SocialMediaPlatform) addPost(post Post) {
sm.Posts = append(sm.Posts, post)
}
func (sm *SocialMediaPlatform) getUserPosts(userID int) []Post {
var userPosts []Post
for _, post := range sm.Posts {
if post.UserID == userID {
userPosts = append(userPosts, post)
}
}
return userPosts
}
func (sm *SocialMediaPlatform) searchPostsByKeyword(keyword string) []Post {
var result []Post
for _, post := range sm.Posts {
if strings.Contains(post.Content, keyword) {
result = append(result, post)
}
}
return result
}
这个代码示例实现了一个简单的社交媒体平台,包括用户和帖子的结构体、添加用户和帖子的方法,以及根据用户和关键字搜索帖子的功能。示例中还展示了如何添加用户和帖子,并显示每个用户发布的帖子。希望这个示例对您有所帮助!如果您有任何其他问题,我会很乐意回答。
标签:int,代码,socialMedia,ID,sm,Post,例题,社交,post From: https://blog.51cto.com/u_16018846/7726297